简体   繁体   English

c#DLLImport以char *作为参数调用c ++方法

[英]c# DLLImport calling c++ method with char* as parameter

I got an external DLL (c++) with the follwing method: 我使用以下方法获得了一个外部DLL(c ++):

 void _stdcall Set_Config(char* config)

I use the following c# code to call the method: 我使用以下c#代码调用该方法:

[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. 但是,当我执行我的C#代码时,我得到了acces违反异常或System.Runtime.InteropServices.SEHException。 (My dll is 32 bit, and my c# compiler compiles to 32 bit) (我的dll是32位,而我的c#编译器编译为32位)

I also tried to replace String config with Stringbuilder, but the same result. 我也尝试用Stringbuilder替换String config,但是结果相同。

Can someone help me with this problem or give some example code how i have to call the c++ method? 有人可以帮助我解决这个问题,或者给出一些示例代码,我该如何调用c ++方法?

CharSet.Auto will encode as UTF-16. CharSet.Auto将编码为UTF-16。 But your function accepts char* and so the text is encoded as 8 bit text, presumably ANSI. 但是您的函数接受char* ,因此文本被编码为8位文本,大概是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* . 另一方面,奇怪的是参数是char*而不是const char* Either the developer doesn't know how to use const , or perhaps the function really does send data back to the caller. 开发人员可能不知道如何使用const ,或者该函数确实确实会将数据发送回调用方。

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. 您需要传递一个StringBuilder但是无法告诉DLL可用的缓冲区有多大。 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. 您必须传递IntPtr ,它是指向字符串的原始指针。 (From my memories, Marshal.StringToBSTR ) (从我的记忆中, Marshal.StringToBSTR

public static extern void Set_Config(IntPtr config);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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