简体   繁体   中英

c# DLLImport calling c++ method with char* as parameter

I got an external DLL (c++) with the follwing method:

 void _stdcall Set_Config(char* config)

I use the following c# code to call the method:

[DllImport(DllName,CharSet=CharSet.Auto)]
    public static extern void Set_Config(String config);

But when i execute my c# code i get either an acces violation exception or an System.Runtime.InteropServices.SEHException. (My dll is 32 bit, and my c# compiler compiles to 32 bit)

I also tried to replace String config with Stringbuilder, but the same result.

Can someone help me with this problem or give some example code how i have to call the c++ method?

CharSet.Auto will encode as UTF-16. But your function accepts char* and so the text is encoded as 8 bit text, presumably ANSI.

[DllImport(DllName, CharSet = CharSet.Ansi)]
public static extern void Set_Config(string config);

Calling the function is trivial.

I am assuming that the string is being passed into the function. On the other hand, it is odd that the parameter is char* rather than const char* . Either the developer doesn't know how to use const , or perhaps the function really does send data back to the caller.

If the data flows the other way, then you are in trouble. You'd need to pass a StringBuilder but you've no way to tell the DLL how large a buffer is available. If the data is flowing the other way then the code looks like this:

[DllImport(DllName, CharSet = CharSet.Ansi)]
public static extern void Set_Config(StringBuilder config);

Call the function like this:

StringBuilder config = new StringBuilder(256); // cross your fingers
Set_Config(config);

Either way, you need to be more clear as to what this function is actually doing. You cannot hope to call this function until you know whether to pass data in, or receive data out.

You have to pass an IntPtr which is a raw pointer to your string. (From my memories, Marshal.StringToBSTR )

public static extern void Set_Config(IntPtr config);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM