将字符串从本机 C++ DLL 传递到 C# 应用程序

2024-03-23

我用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;
}

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);

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"

}

我尝试通过引用从 C# 传递参数,并让 C++ DLL 填充该参数。即使我已经验证 DLL 中的值是正确的,乱码还是会传递到 C# 应用程序。

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


Use a StringBuilder传递本机代码可以填充的字符数组(请参阅固定长度字符串缓冲区 http://msdn.microsoft.com/en-us/library/s9ts558h.aspx#cpcondefaultmarshalingforstringsanchor3).

声明函数:

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

Use it:

// 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将字符串从本机 C++ DLL 传递到 C# 应用程序 的相关文章

随机推荐