C++ 常量WCHAR*myVar与常量char*myVar
我已经开发了一个小型bmp到jpg转换器。 下面的代码正在工作,并根据需要提供准确的结果C++ 常量WCHAR*myVar与常量char*myVar,c++,c,winapi,C++,C,Winapi,我已经开发了一个小型bmp到jpg转换器。 下面的代码正在工作,并根据需要提供准确的结果 BOOLEAN convertBMPtoJPG(const WCHAR *src_bmp_path,const WCHAR *dest_jpeg_path); 然后调用函数as const WCHAR *src_bmp_path = L"test.bmp"; const WCHAR *dest_jpeg_path= L"test.jpg"; convertBMPtoJPG(src_bmp_path,des
BOOLEAN convertBMPtoJPG(const WCHAR *src_bmp_path,const WCHAR *dest_jpeg_path);
然后调用函数as
const WCHAR *src_bmp_path = L"test.bmp";
const WCHAR *dest_jpeg_path= L"test.jpg";
convertBMPtoJPG(src_bmp_path,dest_jpeg_path);
但是,我需要按照以下方式更改函数(根据我得到的要求),但这样做会导致编译错误
BOOLEAN convertBMPtoJPG(char *src_bmp_path,char *dest_jpeg_path);
然后函数将被调用为(尽管我需要遵循上面的原型)
关于stackover的另一个问题提供了太多关于Win32类型的信息,但是我仍然无法解决这个问题。
我对Win32 API不是很在行,请在以后的方法中指导我哪里出了问题
编辑:
错误消息:
错误C2664:'Gdiplus::Status Gdiplus::Image::Save(const WCHAR*、const CLSID*、const Gdiplus::EncoderParameters*)':无法将参数1从'char*'转换为'const WCHAR*'
1> 指向的类型是不相关的;转换需要重新解释转换、C样式转换或函数样式转换。好吧,看起来您的编译是为了Unicode支持。可以找到Win32数据类型的列表 WCHAR定义为-
A 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef wchar_t WCHAR;
这里有一个链接,显示了如何在各种字符串类型之间转换,例如使用MultiByteToWideChar()
(就像Win32 API Ansi函数在内部调用Win32 API Unicode函数时所做的那样),例如:
鉴于您决定让我们猜测编译错误是什么,可能您缺少了
const
?您的字符*字符串是什么格式?是UTF-8吗?它在用户的默认代码页中吗?可能是不同的代码页吗?在CP\u ACP
中有一个很大的假设。您确实需要知道字符串的编码方式你被交了,如果所需的路径不能在编码中表示,你会怎么做。谢谢Remy,我已经找到并修复了它。调用'stat=image->Save(dest\u jpeg\u path,&encoderClsid,NULL)“假设只接受WCHAR*,但我认为我没有正确地将字符串传递给函数。@AdrianMcCarthy:同意,这就是为什么现代代码不应该再使用Ansi fyed。最好只编写针对Unicode的代码。但要求是公开Ansi版本的convertBMPtoJPG()
,因此一种解决方法是让该函数将一个额外的代码页参数作为输入,并将其传递给towstring()
,这样它就可以将其传递给MultiByteToWideChar()
。至少调用方有责任知道源代码char*
值的编码。@RemyLebeau:除了使用char*
,我们实际上不知道要求是什么。这可能意味着UTF-8或系统默认ANSI代码页以外的其他编码。@AdrianMcCarthy:更有理由让调用者将char*
值的实际编码传递给char
版本的convertBMPtoJPG()
,以便在需要时将其正确转换为Unicode。
A 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef wchar_t WCHAR;
std::wstring towstring(const char *src)
{
std::wstring output;
int src_len = strlen(src);
if (src_len > 0)
{
int out_len = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0);
if (out_len > 0)
{
output.resize(out_len);
MultiByteToWideChar(CP_ACP, 0, src, src_len, &output[0], out_len);
}
}
return output;
}
BOOLEAN convertBMPtoJPG(char *src_bmp_path,char *dest_jpeg_path)
{
return convertBMPtoJPG(towstring(src_bmp_path).c_str(), towstring(dest_jpeg_path).c_str());
}
BOOLEAN convertBMPtoJPG(const WCHAR *src_bmp_path, const WCHAR *dest_jpeg_path)
{
// your existing conversion logic here...
}