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

落花浮王杯 提交于 2021-01-28 19:08:29

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/28497514/c-sharp-dllimport-calling-c-method-with-char-as-parameter

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