c#DLLImport以char *作为参数调用c ++方法 [英] c# DLLImport calling c++ method with char* as parameter

查看:58
本文介绍了c#DLLImport以char *作为参数调用c ++方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方法获得了一个外部DLL(c ++):

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

 void _stdcall Set_Config(char* config)

我使用以下c#代码调用该方法:

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

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

但是当我执行我的C#代码时,我得到了acces违例异常或System.Runtime.InteropServices.SEHException.(我的dll是32位,而我的C#编译器编译为32位)

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)

我还尝试用Stringbuilder替换String config,但结果相同.

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

有人可以帮助我解决这个问题,或者给出一些示例代码,我该如何调用c ++方法?

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

推荐答案

CharSet.Auto 将编码为UTF-16.但是您的函数接受 char * ,因此文本被编码为8位文本,大概是ANSI.

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

调用该函数很简单.

我假设字符串正在传递到函数中.另一方面,奇怪的是参数是 char * 而不是 const char * .开发人员可能不知道如何使用 const ,或者该函数确实确实会将数据发送回调用方.

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.

如果数据以其他方式流动,则您有麻烦.您需要传递一个 StringBuilder ,但是您无法告诉DLL可用的缓冲区有多大.如果数据以另一种方式流动,则代码如下所示:

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

像这样调用函数:

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.

这篇关于c#DLLImport以char *作为参数调用c ++方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆