且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从C#将const char *传递给C函数?

更新时间:2023-02-12 17:27:48

看起来你会使用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)] 

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



另请参阅 Microsoft关于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.