在LPCSTR中追加BSTR [英] Appending BSTR in a LPCSTR
问题描述
我有一个类函数接收一个BSTR。在我的类中,我有一个成员变量是LPCSTR。现在我需要附加BSTR ins LPCSTR。我怎么能这样做。
这是我的函数。
I have a class function which is receving a BSTR. In my class I have a member variable which is LPCSTR. Now I need to append BSTR ins LPCSTR. How I can do that. Here is my function.
void MyClass::MyFunction(BSTR text)
{
LPCSTR name = "Name: ";
m_classMember = name + text; // m_classMember is LPCSTR.
}
在我的m_classMember中我希望这个函数值后应该是Name:text_received_in_function 。
in my m_classMember I want that after this function value should be "Name: text_received_in_function". How i can do that.
推荐答案
使用Microsoft特定的 _bstr_t
类,本机。像
Use the Microsoft specific _bstr_t
class, which handles the ANSI/Unicode natively. Something like
#include <comutils.h>
// ...
void MyClass::MyFunction(BSTR text)
{
_bstr_t name = "Name: " + _bstr_t(text, true);
m_classMember = (LPCSTR)name;
}
是你几乎想要的。然而,正如注释中所指出的,你必须管理 m_classMember
和连接的字符串的生命周期。在上面的例子中,代码可能会崩溃。
is what you almost want. However, as pointed out by the remarks, you have to manage the lifetime of m_classMember
and the concatened string. In the example above, the code is likely to crash.
如果你拥有 MyClass
添加另一个成员变量:
If you own the MyClass
object, you could simply add another member variable:
class MyClass {
private:
_bstr_t m_concatened;
//...
};
,然后使用 m_classMember
m_concatened
的字符串内容。
and then use m_classMember
as a pointer to the string content of m_concatened
.
void MyClass::MyFunction(BSTR text)
{
m_concatened = "Name: " + _bstr_t(text, true);
m_classMember = (LPCSTR)m_concatened;
}
否则,在分配 m_classMember
,你应该以与分配它相同的方式释放它(
free
, delete []
等等),并创建一个新的 char *
数组,在其中复制连接字符串的内容。类似
Otherwise, prior to the assignment of m_classMember
, you should free it in the same way you allocated it (free
, delete []
, etc), and create a new char*
array in which you copy the content of the concatened string. Something like
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;
}
应该做这项工作。
这篇关于在LPCSTR中追加BSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!