将字符串从Native C++ DLL传递到C#App

Jac*_*rry 2 c# c++ string dllimport visual-studio-2008

我用C++编写了一个DLL.其中一个函数写入字符数组.

C++函数

EXPORT int xmain(int argc, char argv[], char argv2[])
{
    char  pTypeName[4096];
    ...
    //Other pTypeName ends up populated with "Portable Network Graphics"
    //This code verifies that pTypeName is populated with what I think it is:
    char szBuff[64];
    sprintf(szBuff, pTypeName, 0);
    MessageBoxA(NULL, szBuff, szBuff, MB_OK);
    //The caption and title are "Portable Network Graphics"

    ...
    //Here, I attempt to copy the value in pTypeName to parameter 3.
    sprintf(argv2, szBuff, 0);

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

C#导入

    //I believe I have to use CharSet.Ansi because by the C++ code uses char[],
    [DllImport("FirstDll.dll", CharSet=CharSet.Ansi)]
    public static extern int xmain(int argc, string argv, ref string zzz);
Run Code Online (Sandbox Code Playgroud)

C#功能

private void button2_Click(object sender, EventArgs e)
{
    string zzz = ""; 
    int xxx = xmain(2, @"C:\hhh.bmp", ref zzz);
    MessageBox.Show(zzz);

    //The message box displays
    //MessageBox.Show displays "IstuÈst¼ÓstÄstlÄstwÄstiÑstõÖstwÍst\
    // aÖst[ÖstÃÏst¯ÄstÐstòÄstŽÐstÅstpÅstOleMainThreadWndClass"

}
Run Code Online (Sandbox Code Playgroud)

我试图通过引用从C#传递参数,并让C++ DLL填充参数.尽管我已经验证了DLL中的值是正确的,但是乱码会传递给C#应用程序.

如何将正确的字符串值写入C#字符串?

Bra*_*ger 5

使用a StringBuilder传递本机代码可以填充的字符数组(请参阅固定长度字符串缓冲区).

声明函数:

[DllImport("FirstDll.dll", CharSet=CharSet.Ansi)]
public static extern int xmain(int argc, string argv, StringBuilder argv2);
Run Code Online (Sandbox Code Playgroud)

用它:

// allocate a StringBuilder with enough space; if it is too small,
// the native code will corrupt memory
StringBuilder sb = new StringBuilder(4096);
xmain(2, @"C:\hhh.bmp", sb);
string argv2 = sb.ToString();
Run Code Online (Sandbox Code Playgroud)