简体   繁体   English

将C ++字符串发送到C#字符串。 互操作

[英]Send C++ string to C# string. Interop

I am new to inter process communication and need some help. 我是进程间通信的新手,需要一些帮助。 I want to be able to send a string from a C++ program to a C# program. 我希望能够将字符串从C ++程序发送到C#程序。 My problem is that the resultant string is gibberish. 我的问题是结果字符串是乱码。 Here is my code: 这是我的代码:

Sending program (C++): 发送程序(C ++):

void transmitState(char* myStr)
{

    HWND hWnd = ::FindWindow(NULL, _T("myApp v.1.0"));
    if (hWnd)
    {
        COPYDATASTRUCT cds;
        ::ZeroMemory(&cds, sizeof(COPYDATASTRUCT));
        cds.dwData = 0;
        cds.lpData = (PVOID) myStr;
        cds.cbData = strlen(myStr) + 1;

        ::SendMessage(hWnd, WM_COPYDATA, NULL, (LPARAM)&cds);
    }
}   

And the receiving program (C#) (I have already overridden the WndProc): 和接收程序(C#)(我已经重写了WndProc):

private void OnCopyData(ref Message m)
{
    COPYDATASTRUCT cds = new COPYDATASTRUCT();
    cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));

    String myStr;
    unsafe
    {
        myStr = new String((char*) cds.lpData);
    }

    label1.Text = myStr;
}

char* in C++ is ANSI character string (usually one byte per character), char* in C# is Unicode character string (like WCHAR* - two bytes per character). C ++中的char *是ANSI字符串(通常每个字符一个字节),C#中的char *是Unicode字符串(例如WCHAR *-每个字符两个字节)。

You in fact reinterpret_cast from char* to WCHAR*. 实际上,您实际上是从char *到WCHAR *的reinterpret_cast。 This won't work. 这行不通。 Use MultiByteToWideChar() on C++ side to convert. 在C ++端使用MultiByteToWideChar()进行转换。

Your string in C++ is ANSI. 您在C ++中的字符串是ANSI。 You need to convert to Unicode somewhere for C#. 您需要将C#转换为Unicode。 It's been a couple of years since I did interop, so someone else will have to tell you exactly how to do that. 自从我进行互操作以来已经有两年了,所以其他人将不得不告诉您确切的操作方法。

You'll have to convert your character array from ASCII to Unicode somehow. 您必须以某种方式将字符数组从ASCII转换为Unicode。 Here is a page that may help do it from the C# side . 这是一个可以从C#方面帮助您完成工作的页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM