如何将 char* 转换为 LPCWSTR?
我知道这已经在关于 SO 的几个问题中讨论过,但这些解决方案都没有对我有用.
我以 char*
开头,因为这是用于从 VBA 调用的 DLL,并且 char*
是 VBA 将字符串传递给 DLL 所必需的.
我需要返回一个 LPCWSTR
因为这是我试图调用的 API 函数的输入参数,我无法通过从 Unicode 切换到多字节字符集来启用转换属性窗口,因为 API 有这样的代码:
#if !defined(UNICODE) &&!defined(NOUNICODE)#error UNICODE 未定义.必须为正确的 API 参数定义 UNICODE.#万一
我试过了:
LPCWSTR convertCharArrayToLPCWSTR(char* charArray){const char* cs=charArray;wchar_t 文件名[4096] = {0};MultiByteToWideChar(0, 0, cs[1], strlen(cs[1]), filename, strlen(cs[1]));}
给出了这些错误:
错误 C2664:strlen":无法将参数 1 从const char"转换为const char *"错误 C2664:MultiByteToWideChar":无法将参数 3 从const char"转换为LPCCH"
我试过这个(相同的函数头),大致改编自这篇文章:
size_t retVal;const char * cs = charArray;size_t 长度=strlen(cs);wchar_t * buf = new wchar_t[length]();//值初始化为 0(见下文)size_t wn = mbsrtowcs_s(&retVal,buf,20, &cs, length + 1, NULL);返回缓冲区;
编译没问题,但是当我向它传递一个示例字符串xyz.xlsx"时,mbsrtowcs_s()
将 buf
设置为空字符串:L""
那么,我该如何进行这种转换?
解决方案由于 cs
是一个 const char*
,cs[1]
是一个 const char
.C++ 不会为您将其转换为指针,因为在大多数情况下这是没有意义的.
如果要跳过第一个字符,您可以改为使用 &cs[1]
或 cs+1
.(这就是传递指向第 1 个元素的指针时所做的;在 C++ 中,索引从 0 开始.)如果意图传递整个字符串,则只需传递 cs
.>
I know this has already been discussed in several questions on SO, but none of those solutions have worked for me.
I start with a char*
because this is for a DLL that will be called from VBA, and char*
is necessary for VBA to pass a string to the DLL.
I need to return a LPCWSTR
because that's the input parameter for the API function I'm trying to call, and I can't enable casting by switching from Unicode to multi-byte character set in the Properties window, because the API has this code:
#if !defined(UNICODE) && !defined(NOUNICODE)
#error UNICODE is not defined. UNICODE must be defined for correct API arguments.
#endif
I tried this:
LPCWSTR convertCharArrayToLPCWSTR(char* charArray)
{
const char* cs=charArray;
wchar_t filename[4096] = {0};
MultiByteToWideChar(0, 0, cs[1], strlen(cs[1]), filename, strlen(cs[1]));
}
which gave these errors:
error C2664: 'strlen' : cannot convert parameter 1 from 'const char' to 'const char *'
error C2664: 'MultiByteToWideChar' : cannot convert parameter 3 from 'const char' to 'LPCCH'
I tried this (same function header), loosely adapted from this post:
size_t retVal;
const char * cs = charArray;
size_t length=strlen(cs);
wchar_t * buf = new wchar_t[length](); // value-initialize to 0 (see below)
size_t wn = mbsrtowcs_s(&retVal,buf,20, &cs, length + 1, NULL);
return buf;
This compiled ok, but when I passed it an example string of "xyz.xlsx", mbsrtowcs_s()
set buf
to an empty string: L""
So, how do I make this conversion?
解决方案Since cs
is a const char*
, cs[1]
is a const char
. C++ won't convert it to a pointer for you, because in most cases that doesn't make sense.
You could instead say &cs[1]
or cs+1
if the intent is to skip the first char. (That's what you're doing when you pass a pointer to the 1th element; in C++, indexes start at 0.) If the intent is to pass the whole string, then just pass cs
.
相关文章