问题描述
我知道这已经在SO的几个问题中讨论过了,但是这些解决方案都没有为我工作。
I know this has already been discussed in several questions on SO, but none of those solutions have worked for me.
我从一个 char *
,因为这是一个将从VBA调用的DLL,并且 char *
是VBA将字符串传递给DLL所必需的。
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.
我需要返回一个 LPCWSTR
,因为这是我要调用的API函数的输入参数,并且我无法通过在属性窗口中从Unicode切换为多字节字符集来启用转换,因为API具有以下代码:
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
我试过:
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]));
}
出现以下错误:
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'
我试过这个:
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;
这个编译好,但是当我传递一个示例字符串xyz.xlsx c $ c> mbsrtowcs_s()将 buf
设置为空字符串: L
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?
推荐答案
cs
是 const char *
, cs [1]
是一个 const char
。 C ++不会将它转换为指针,因为在大多数情况下这是没有意义的。
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.
你可以改为&如果意图是跳过第一个字符,则cs [1]
或 cs + 1
(这就是当你传递一个指针到第1个元素时,你在做什么;在C ++中,索引从0开始。)如果意图是传递整个字符串,那么只需传递 cs
。
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
.
这篇关于如何将char *转换为LPCWSTR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!