gpt4 book ai didi

c# - 将字符串从 native C++ DLL 传递到 C# 应用程序

转载 作者:搜寻专家 更新时间:2023-10-31 00:18:19 26 4
gpt4 key购买 nike

我用 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# 字符串?

最佳答案

使用 StringBuilder 传递 native 代码可以填充的字符数组(参见 Fixed-Length String Buffers )。

声明函数:

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

使用它:

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

关于c# - 将字符串从 native C++ DLL 传递到 C# 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10856127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com