首页 > 解决方案 > Convert a UTF-16 buffer into CString if only byte size is Known?

问题描述

When using sqlite3_column_text16 and sqlite3_column_bytes16 in https://www.sqlite.org/c3ref/column_blob.html , I can only get a pointer to the UTF-16 text buffer, as well as the number of bytes in the buffer.

Now I need to convert such a buffer into a CString object. How to do so? It seems that CString only has the following constructor:

CString( LPCTSTR lpch, int nLength );  // requires LPCTSTR and number of chars, not bytes
CString( LPCWSTR lpsz );               // requires null-terminiated Unicode buffer

Both seems not appropriate for my case.

标签: stringmfc

解决方案


CString( LPCTSTR lpch, int nLength )将完成这项工作。它只需要一个LPCTSTR演员,或者LPCWSTR在这种情况下。nLength应该是大小除以 2 来说明wchar_t

CStringW如果您的程序不是 Unicode,请使用。

例子:

//create a buffer (buf) and copy a wide string in to it
const wchar_t *source = L"ABC";
int len = wcslen(source);
int bytesize = len * 2;

BYTE *buf = new BYTE[bytesize + 2]; //optional +2 for null terminator
memcpy(buf, source, bytesize);

//copy buf into destination CString
CString destination((LPCWSTR)buf, bytesize / 2);
delete[]buf;

MessageBoxW(0, destination, 0, 0);

buf并且bytesize来自数据库,所以只需输入:

CString destination((LPCWSTR)buf, bytesize / 2);    
//or
CStringW destination((LPCWSTR)buf, bytesize / 2);

推荐阅读