使用 Microsoft 特定的_bstr_t
类,它本机处理 ANSI/Unicode。就像是
#include <comutils.h>
// ...
void MyClass::MyFunction(BSTR text)
{
_bstr_t name = "Name: " + _bstr_t(text, true);
m_classMember = (LPCSTR)name;
}
几乎是你想要的。但是,正如评论所指出的,您必须管理m_classMember
连接字符串的生命周期。在上面的示例中,代码很可能会崩溃。
如果您拥有该MyClass
对象,您可以简单地添加另一个成员变量:
class MyClass {
private:
_bstr_t m_concatened;
//...
};
然后m_classMember
用作指向字符串内容的指针m_concatened
。
void MyClass::MyFunction(BSTR text)
{
m_concatened = "Name: " + _bstr_t(text, true);
m_classMember = (LPCSTR)m_concatened;
}
否则,在分配 之前m_classMember
,您应该以分配它的相同方式释放它(free
、delete []
等),并创建一个新char*
数组,在其中复制连接字符串的内容。就像是
void MyClass::MyFunction(BSTR text)
{
_bstr_t name = "Name: " + _bstr_t(text, true);
// in case it was previously allocated with 'new'
// should be initialized to 0 in the constructor
delete [] m_classMember;
m_classMember = new char[name.length() + 1];
strcpy_s(m_classMember, name.length(), (LPCSTR)name);
m_classMember[name.length()] = 0;
}
应该做的工作。