我是 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*
的参数
最佳答案
你需要做这样的事情......
CHandler::GetData 调用 COM 接口(interface)获取 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接口(interface)方法定义
语言: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);
}
关于c# - 将 ATL::CComBSTR 转换为 BSTR*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33233017/