我对C ++很新。我创建了我的C#DLL。我创建了托管C ++ DLL并在我的C#项目中引用它。我想从C#dll返回char*
中的字符串值问题是,我无法将CComBSTR
转换为BSTR
?
UINT CHandler::GetData( UINT idx, char* lName)
{
HRESULT hRes= m_p->GetData(idx, CComBSTR(lName));
}
Error: Fehler by CComBSTR(lNmae): 977 IntelliSense: It is no possible conversion of ""ATL::CComBSTR"" in ""BSTR *"" available.
我的C#函数有第二个类型为BSTR*
答案 0 :(得分:0)
你需要做这样的事情......
CHandler :: GetData调用COM接口来获取char * lName
了解如何释放已分配的内存。
UINT CHandler::GetData(UINT idx, char* lName)
{
BSTR bstrName;
HRESULT hRes= m_p->GetData(&bstrName);
char *p= _com_util::ConvertBSTRToString(bstrName);
strcpy(lName,p); //lName needs to be large enough to hold the string pointed to by p
delete[] p; //ConvertBSTRToString allocates a new string you will need to free
//free the memory for the string
::SysFreeString(bstrName);
}
COM接口方法定义
语言:C ++,请将其翻译为C# 基本上,您需要在c#方法中分配BSTR。
查看COM方法如何分配和返回内存
HRESULT CComClass::GetData(long idx, BSTR* pbstr)
{
try
{
//Let's say that m_str is CString
*pbstr = m_str.AllocSysString();
//...
}
catch (...)
{
return E_OUTOFMEMORY;
}
// The client is now responsible for freeing pbstr.
return(S_OK);
}