Passing String from Native C++ DLL to C# App

匆匆过客 提交于 2019-12-06 09:45:57

Use a StringBuilder to pass a character array that native code can fill in (see Fixed-Length String Buffers).

Declare the function:

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

Give some other information to the DLLImport call. Look at the following example of my own:

[DllImport("tcpipNexIbnk.dll", EntryPoint = "SendData", CallingConvention = CallingConvention.Cdecl)]
    public static extern int Send([MarshalAs(UnmanagedType.LPWStr)]string message);

Notice two things, the CallingConvention parameter: CallingConvention = CallingConvention.Cdecl)

Use that as it is.

And then just behind the c# string type, you can play with the different Unmanaged types using the MarshalAS instruction, that will cast your C# string parameter to the native string type you have in your c++ program:

public static extern int Send([MarshalAs(UnmanagedType.LPWStr)]string message);

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!