[英]Passing String from Native C++ DLL to C# App
我已经用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
传递本机代码可以填充的字符数组(请参见“ 固定长度的字符串缓冲区” )。
声明功能:
[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();
将其他一些信息提供给DLLImport调用。 看下面我自己的例子:
[DllImport("tcpipNexIbnk.dll", EntryPoint = "SendData", CallingConvention = CallingConvention.Cdecl)]
public static extern int Send([MarshalAs(UnmanagedType.LPWStr)]string message);
注意两件事,CallingConvention参数:CallingConvention = CallingConvention.Cdecl)
照原样使用。
然后紧随C#字符串类型之后,您可以使用MarshalAS指令使用不同的非托管类型,该指令会将C#字符串参数转换为您在c ++程序中具有的本机字符串类型:
public static extern int Send([MarshalAs(UnmanagedType.LPWStr)]string message);
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.