为const char *在C#中? [英] const char* in C#?

查看:1375
本文介绍了为const char *在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 无效set_param(为const char *数据)
 

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

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

  2. 我如何交出平,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 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:

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

  2. 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.

这篇关于为const char *在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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