您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

如何把 unsigned char* 轉換成 const char*

編輯:iOS 開發綜合

在 C/C++ 或 Objective-C++ 混寫的場景裡,常需要把位元組緩衝區當成 C 字串傳給 API。最直觀的途徑是借道 CString 完成轉換。

做法

unsigned char *Writebuf;
// ... 對 Writebuf 進行讀寫操作之後

CString str1;
str1.Format("%s", Writebuf);          // unsigned char* → CString

const char *str2 = (LPCTSTR)str1;     // CString → const char*

為什麼能這樣轉

整條路徑是:unsigned char* 透過 Format 進入 CString,再由 CString 強制轉型成 LPCTSTR 得到 const char*。

CString 繼承自 CStringT,內部維護一個以 null 結尾的緩衝區,並提供了 operator LPCTSTR() 轉換運算子,因此可以直接轉型取出底層指標。

三個要注意的地方

型別是否相符取決於字元集設定。 LPCTSTR 在 Unicode 專案中等價於 const wchar_t*,在 Multi-Byte 專案中等價於 const char*。如果你的專案設為 Unicode 卻想要 const char*,這樣寫會編譯失敗或資料錯亂,此時應改用 CT2A 巨集明確轉換。

Format 的 %s 會在遇到第一個 null 位元組時停止。 若 Writebuf 是二進位資料(例如影像壓縮後的串流),裡面很可能夾雜 0x00,用 %s 會導致內容被截斷。這種情況請改用 CString(str, length) 的建構方式,或直接避開 CString 以 std::string 搭配長度處理。

轉出的指標生命週期依賴 CString 物件。 str2 指向的記憶體由 str1 擁有,一旦 str1 離開作用域或內容被修改,str2 就變成指標懸空。因此不要把 str2 存起來之後才用。

不用 CString 的替代寫法

若不想引入 MFC/ATL,用標準 C++ 也能達成同樣目的:

unsigned char *Writebuf = ...;

// 方式一:直接轉型(資料為純文字且以 null 結尾時)
const char *str2 = reinterpret_cast<const char *>(Writebuf);

// 方式二:明確指定長度,適合含 null 的資料
std::string str3(reinterpret_cast<char *>(Writebuf), byteLength);
const char *str4 = str3.c_str();

方式二更嚴謹,因為它顯式帶入長度,不會被內嵌的 null 字元截斷。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved