本文介绍了如何从C#将const char *传递给C函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从我的C#应用​​程序中的外部DLL调用一个简单的C函数。这个函数定义为

  void set_param(const char * data)
pre>

现在我使用这个功能有一些问题:


  1. 如何在C#-code中指定这个const? public static extern void set_param(sbyte * data)似乎错过了const部分。


  2. 调用此函数时如何交出一个简单的8位C字符串?调用 set_param(127.0.0.1)导致错误消息,无法从'string'转换为'sbyte '*



解决方案

看起来你会使用ANSI char set,所以你可以这样声明P / Invoke:

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

.NET编组器处理复制字符串并将数据转换为正确的类型。 / p>

如果您使用不平衡堆栈发生错误,则需要设置调用约定以匹配C DLL,例如:

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

请参阅大量使用Windows API函数的示例。



另请参阅。


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.

这篇关于如何从C#将const char *传递给C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:55