无法从 C++ 检索 wchar_t* 到 C#

Unable to retrieve wchar_t* from C++ to C#

我一直在尝试从 DLL 调用 API,如下所示:

 [DllImport(@"TELCompress.dll", EntryPoint = "TELMonDecode", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
    public static extern int TELMonDecode(ref bool a, ref bool b, byte[] ab, System.IntPtr pDestBuf, int j, int byteCount);

从 C# 代码调用

int returnval = TELMonDecode(ref a, ref b, bytes, destPnt, k, bytesRec);

DLL 中的 C++ 代码

__declspec(dllexport) int TELMonDecode(bool *bUnicode, bool *bCompress, BYTE *pSourceBuf, wchar_t* pDestBuf, int pDestBufSize,int byteCount)

{
 ...
    CString decodedMsg = _T("<Empty>");
    int erc = DecodeByteStream(bUnicode, bCompress, pSourceBuf, &decodedMsg);

    ::MessageBox(NULL,L"Decoding byte done",L"Caption",0);
    pDestBuf = decodedMsg.GetBuffer();
    ::MessageBox(NULL,pDestBuf,L"Caption in TELMonDecode",0);
 ...
}

我在这里提到了很多链接,但我仍然无法弄清楚我做错了什么。 请指导。

在 wchar_t* 上使用 BSTR*,您应该能够在 C# 端使用 ref String

感谢您的评论。这很有帮助。

现在代码如下所示 C# 代码

    [DllImport(@"TELCompress.dll", EntryPoint = "TELMonDecode", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
    public static extern int TELMonDecode(ref bool a, ref bool b, byte[] ab, ref String pDestBuf, int j, int byteCount);
... //Some code here
//Call to the C++ function 
 int returnval = TELMonDecode(ref a, ref b, bytes, ref receiveStr, k, bytesRec);

TELCompress.dll

中的 C++ 代码
__declspec(dllexport) int TELMonDecode(bool *bUnicode, bool *bCompress, BYTE *pSourceBuf, BSTR* pDestBuf, int pDestBufSize,int byteCount)
{
  CString decodedMsg = _T("<Empty>");
  //Code to copy data in decodedMsg 
  CComBSTR tempBstrString(decodedMsg.GetBuffer()); //test 
  tempBstrString.CopyTo(pDestBuf);
 .... //Some more code
return 0;
}

它有效,在 C# 代码中可以看到该字符串,之前显示的是空字符串。

非常感谢所有宝贵的反馈和评论。 -梅加