在托管代码和非托管代码之间传递字符串时,我遇到了很多问题。搜索和组合代码后,我有一个似乎有效的解决方案。但我仍然不确定这是否是正确的实施。
在我的代码中,c#将委托函数传递给c ++。现在c ++在需要时调用该函数。 C ++需要发送字符串来回调我正在使用BSTR的函数。这就是我实现它的方式。
C#
[DllImport("xyz.dll")]
public static extern void SetCallback(Callback fn);
public delegate void Callback([MarshalAs(UnmanagedType.BStr)]string str);
public Callback mInstance;
private void Handler(string text)
{
NotifyListeners_uccx(text);
}
Private void setcallback(){
mInstance = new Callback(Handler);
SetCallback(mInstance); }
C ++
typedef void (__stdcall *Callback) (BSTR str);
Callback Handler;
extern "C"
{
void __declspec(dllexport) __stdcall SetCallback(Callback handler);
void __declspec(dllexport) __stdcall SendReceiveMessage(BSTR arr1);
}
void __stdcall SendReceiveMessage(BSTR arr1) {
Handler(arr1);
}
void __stdcall SetCallback(Callback handler1) {
Handler = handler1;
}
void CCall::sendmsg(FILE *fp)
{
//do some work
try
{
char *str;
char *Tag_t;
str = new char[2048];
Tag_t = new char[1024];
sprintf(str, "<body><Tag1>%d</Tag1 ><Tag2>%s</Tag2>",sumNum, SumString);
for (int i = 0; i < sumNum; i++)
{
sprintf(Tag_t,"<Tag3>%s</Tag3>",tagString3,m_csqIDs[i],i);
strcat(str,Tag_t);
}
strcat(str,"</body>");
int wslen = MultiByteToWideChar(CP_ACP, 0, str, strlen(str), 0, 0);
BSTR bstr = SysAllocStringLen(0, wslen);
MultiByteToWideChar(CP_ACP, 0, str, strlen(str), bstr, wslen);
// Use bstr here
SendReceiveMessage(bstr);
SysFreeString(bstr);
//SysFreeString(bstr);
delete[] str;
delete[] Tag_t;
}
catch(std::bad_alloc& exc)
{
return;
}
}
请建议这是否是正确的方法?