为const char *在C#中?const、char

2023-09-04 01:06:22 作者:不给糖吃就胡闹

我尝试调用一个普通的C函数从外部DLL从我的C#-application。此功能被定义为

 无效set_param(为const char *数据)
 

现在我已经使用这个功能的一些问题:

如何指定这个常量在C# - code? 公开静态外部无效set_param(为sbyte *数据)似乎错过了常量部分

我如何交出平,8位C-串调用这个函数的时候?调用为 set_param(127.0.0.1)导致错误消息无法从字符串转换为为sbyte *'

解决方案

它看起来像您将使用ANSI字符集,所以你可以宣布的P / Invoke,像这样:

  [的DllImport(yourdll.dll,字符集= CharSet.Ansi)
公共静态外部无效set_param([的MarshalAs(UnmanagedType.LPStr)字符串lpString);
 

在.NET编组处理使得字符串拷贝和转换数据,以正确的类型给你。

C 语言中char 和const char 的区别

如果你有一个不平衡的堆栈错误,你将需要设置调用约定,以配合您的C DLL,例如:

  [的DllImport(yourdll.dll,字符集= CharSet.Ansi,CallingConvention = CallingConvention.Cdecl)
 

请参阅 pinvoke.net 获得大量的例子使用Windows API函数。

另请参见微软的文档上pinvoking字符串的。

I try to call a plain C-function from an external DLL out of my C#-application. This functions is defined as

void set_param(const char *data)

Now I have some problems using this function:

How do I specify this "const" in C#-code? public static extern void set_param(sbyte *data) seems to miss the "const" part

How do I hand over a plain, 8 bit C-string when calling this function? A call to set_param("127.0.0.1") results in an error message "cannot convert from 'string' to 'sbyte*'"

解决方案

It looks like you will be using the ANSI char set, so you could declare the P/Invoke like so:

[DllImport("yourdll.dll", CharSet = CharSet.Ansi)]
public static extern void set_param([MarshalAs(UnmanagedType.LPStr)] string lpString);

The .Net marshaller handles making copies of strings and converting the data to the right type for you.

If you have an error with an unbalanced stack, you will need to set the calling convention to match your C DLL, for example:

[DllImport("yourdll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]

See pinvoke.net for lots of examples using Windows API functions.

Also see Microsoft's documentation on pinvoking strings.