6

我正在开发 QT 应用程序,我需要包含纯 C 代码。当我在 code::blocks 中编译这段代码时它是成功的,也许是一个警告,但是当我尝试在 QT creator 中编译它时,我得到了这 4 个错误。

cannot convert 'char*' to 'WCHAR*' for argument '1' to 'UINT GetSystemDirectoryW(WCHAR*, UINT)'
cannot convert 'char*' to 'const WCHAR*' for argument '1' to 'HINSTANCE__* LoadLibraryW(const WCHAR*)'
 cannot convert 'char*' to 'WCHAR*' for argument '1' to 'BOOL 
 cannot convert 'const char*' to 'const WCHAR*' for argument '2' to 'LONG RegQueryValueExW(HKEY__*, const WCHAR*, DWORD*, DWORD*, BYTE*, DWORD*)'

代码在这里>

char systemDirectory[MAX_PATH]; 
GetSystemDirectory(systemDirectory, MAX_PATH); //first error
char kbdLayoutFilePath[MAX_PATH];
kbdLibrary = LoadLibrary(kbdLayoutFilePath); //second error
char kbdName[KL_NAMELENGTH];
GetKeyboardLayoutName(kbdName); //third error
if(RegQueryValueEx(hKey, "Layout File", NULL, &varType, layoutFile, &bufferSize) != ERROR_SUCCESS) //fourth error

我也使用 snprintf 函数,所以我不能只将类型从 char 更改为 WCHAR,因为那样它不会编译 snprintf

snprintf(kbdKeyPath, 51 + KL_NAMELENGTH,
"SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\%s", kbdName);

那么您有任何解决方法的想法吗?首先我尝试将类型从 char 更改为 WCHAR,但随后 snprintf 不起作用,所以我尝试使用 swprinf,但没有成功,因为奇怪的是它没有找到这个函数

int swprintf(wchar_t *wcs, size_t maxlen,
             const wchar_t *format, ...);

但就这个

int swprintf(wchar_t *wcs,
                 const wchar_t *format, ...);

那么我的选择是什么?如何在 c++ 环境中编译纯 C 代码而没有任何错误……或者如何进行正确的类型转换。

4

3 回答 3

4

You are compiling in Unicode mode. You could set your compile to multi-byte strings. The problem that is happening is those windows API functions are macros that check whether you are building Unicode or not and then call either the W or A version of the function (in your code there, the GetSystemDirectory is actually calling GetSystemDirectoryW. So, you can either change your compile to multi-byte strings....or you could explicitly change your api calls to call the A version (i.e. GetSystemDirectoryA)

于 2012-03-19T13:05:25.510 回答
2

You are compiling your project with the UNICODE or _UNICODE define. Check your project settings and remove the define if necessary. To remove the define, you might need to disable unicode support for the whole project.

于 2012-03-19T13:06:21.270 回答
0

切换charWCHAR然后解决您的swprintf问题,只需执行此操作

#define   swprintf   _snwprintf

在 Windows 上,原型swprintf

int swprintf( wchar_t *buffer,const wchar_t *format [,argument] ... );

但是 ISO C 标准需要以下原型swprintf

int swprintf (wchar_t *, size_t, const wchar_t *, ...);

出于这个原因,在 Windows_snwprintf上提供了。

阅读本文了解更多详情

http://msdn.microsoft.com/en-us/library/ybk95axf(v=vs.71).aspx

于 2012-03-19T13:11:38.137 回答