2013-02-20 40 views
0

我開發了一個小型BMP到JPG轉換器。 下面的代碼工作,並提供準確的結果,因爲我需要常量WCHAR * myVar vs const char * myVar

BOOLEAN convertBMPtoJPG(const WCHAR *src_bmp_path,const WCHAR *dest_jpeg_path); 

然後調用功能,

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); 

然後函數將被稱爲,(雖然我需要遵循,就像上面的原型),

char *src_bmp_path = "test.bmp"; 
char *dest_jpeg_path= "test.jpg"; 
convertBMPtoJPG(src_bmp_path,dest_jpeg_path); 

上stackover另一個問題提供了有關的Win32類型的信息太多,但是我還沒有couldn解決不了問題。 我在Win32 API中並不是那麼棒,請指導我後面的方法出了什麼問題。

編輯:

錯誤消息: 錯誤C2664: 'Gdiplus ::狀態Gdiplus ::圖像::保存(常量WCHAR *,常量CLSID *,常量Gdiplus :: EncoderParameters *)':不能將參數1從'char *'轉換爲'const WCHAR *' 1>指向的類型是不相關的;轉換需要reinterpret_cast,C風格演員或功能風格演員

+2

看到您如何決定讓我們猜測編譯錯誤是什麼,也許您錯過了'const'? – James 2013-02-20 18:44:22

+0

你的char *字符串是什麼格式?它是UTF-8嗎?它是否在用戶的默認代碼頁中?它可能是一個不同的代碼頁? – 2013-02-20 19:08:31

回答

2

Image::Save()只接受WCHAR*值,因此您的char*包裝將不得不轉換爲WCHAR*,例如MultiByteToWideChar()(就像Win32 API Ansi函數在內部調用Win32 API Unicode函數時所做的那樣),例如:

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... 
} 
+0

「CP_ACP」中有一個很大的假設。你真的需要知道你正在傳遞的字符串是什麼編碼,以及如果所期望的路徑不能用該編碼表示,會出現什麼樣的情況。 – 2013-02-20 19:10:40

+0

謝謝雷米,我已經知道並修復了。調用'stat = image-> Save(dest_jpeg_path,&encoderClsid,NULL);'假定只接受WCHAR *,但我認爲我沒有正確地將字符串傳遞給函數。 – 2013-02-20 19:13:28

+0

@AdrianMcCarthy:同意,這就是爲什麼現代代碼不應該再被確認的原因。最好編寫僅針對Unicode的代碼。但是需要公開一個Ansi版本的'convertBMPtoJPG()',所以一個解決方法是讓該函數將一個額外的代碼頁參數作爲輸入並傳遞給'towstring()',以便它可以將它傳遞給'MultiByteToWideChar )'。至少這會將調用者的責任置於源char *值的編碼之上。 – 2013-02-20 19:32:16

0

好吧,看起來你正在編譯的Unicode支持。的Win32數據類型的列表,可以發現here

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; 

這裏是一個鏈接顯示如何各種字符串類型之間轉換String Conversion Samples.

相關問題