如何从 C# 将 const char* 传递给 C 函数? [英] How do I pass a const char* to a C function from C#?
问题描述
我尝试从我的 C# 应用程序中的外部 DLL 调用一个普通的 C 函数.该函数定义为
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:
如何在 C# 代码中指定这个const"?
public static extern void set_param(sbyte *data)
似乎错过了const"部分.
How do I specify this "const" in C#-code?
public static extern void set_param(sbyte *data)
seems to miss the "const" part.
如何在调用此函数时传递一个普通的 8 位 C 字符串?调用 set_param("127.0.0.1")
会导致错误消息,"cannot convert from 'string' to 'sbyte'"*.
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'"*.
推荐答案
看起来您将使用 ANSI 字符集,因此您可以像这样声明 P/Invoke:
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);
.NET 编组器处理字符串的副本并将数据转换为适合您的类型.
The .NET marshaller handles making copies of strings and converting the data to the right type for you.
如果您遇到堆栈不平衡的错误,您将需要设置调用约定以匹配您的 C DLL,例如:
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)]
有关使用 Windows API 函数的大量示例,请参阅 pinvoke.net.
See pinvoke.net for lots of examples using Windows API functions.
这篇关于如何从 C# 将 const char* 传递给 C 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!