传递unicode字符串 [英] Passing unicode string
问题描述
大家好,
如何将unicode sring参数传递给函数?是否需要任何转换?
因此,我必须传递Unicode字符串,例如Run(L"Query")..
然后在我的实现代码中,我就这样定义了
Hye all,
How do I pass unicode sring parameter to my function? Was there any conversion needed?
So I have to pass the unicode string for example Run(L"Query")..
Then in my implementation code i define like this
void Run(wchar_t *message)
{
DWORD cbRequest, cbWritten;
cbRequest=sizeof(message);
WriteFile(
hPipe, // Handle of the pipe
message, // Message to be written
cbRequest, // Number of bytes to write
&cbWritten, // Number of bytes written
NULL // Not overlapped
));
}
但是当我进行调试时,写入的消息只是一个,即"Q" ..
but when i do debugging, the message writen was only one namely ''Q''..
How do i correct this?
推荐答案
在这种情况下,必须使用wcslen()
函数而不是sizeof
来获取字符串长度.
You must usewcslen()
function to get string length in this case instead ofsizeof
.
cbRequest = wcslen(message);
Unicode字符在C ++中由wchar_t字符类型表示. Unicode字符串文字以前缀L表示,因为L是Unicode的第一个字母,或者是wide,er.
因此,当您要声明一个C样式的零终止的unicode字符字符串时,请使用:
Unicode characters are represented in C++ by the wchar_t character type. Unicode string literals are denoted by prefixing them with an L, because L is the first letter of Unicode, or wide, er, okay.
So when you want to declare a C style zero terminated string of unicode characters you use:
wchar_t *wide_text = L"I am wide text, feel my girth!";
当您要声明一个采用这种类型的字符串的函数时,可以对它进行原型制作,例如:
and when you want to declare a function that takes this type of string you''d prototype it something like:
void display_message( const wchar_t *text_to_display );
但是,这是C ++,为什么不使用std :: wstring满足所有Unicode文本需求?
干杯,
灰
PS:正如Volodya所说...
这里的问题是sizeof-您告诉它使用指针的大小,而不是要传递给函数的字符数组的大小.您可以使用wcslen之类的东西,但如果使用std :: wstring代替,则代码会更简单.
However this being C++ why not use std::wstring for all your Unicode text needs?
Cheers,
Ash
PS: As Volodya said...
Your problem here is the sizeof - you telling it to use the size of a pointer and not the size of the character array you''re passing into the function. You can use something like wcslen but had you used std::wstring instead the code would have been simpler.
更具体地说明问题.
基本上,您可以在Windows下使用LPCWSTR
type或通过STL使用std::wstring
.
Be more specific about the problem.
Basically you can useLPCWSTR
type under Windows orstd::wstring
using STL.
这篇关于传递unicode字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!