从C#字符串将char *传递给C DLL [英] pass char * to C DLL from C# string
问题描述
我需要在C#应用程序的DLL中使用C函数库。我在使用char *参数调用DLL函数时遇到麻烦:
I need to use a library of C functions in a DLL from a C# application. I am having trouble calling DLL functions with char * arguments:
C DLL:
extern "C" __declspec(dllexport) int CopyFunc(char *, char *);
int CopyFunc(char *dest, char *src)
{
strcpy(dest, src);
return(strlen(src));
}
C#应用程序需要看起来像这样:
the C# app needs to look something like this:
[DllImport("dork.dll")]
public static extern int CopyFunc(string dst, string src);
int GetFuncVal(string source, string dest)
{
return(CopyFunc(dest,source));
}
我已经看到了使用string或StringBuilder或IntPtr替代示例的示例char *是DLL函数原型所需的,但我无法使它们中的任何一个正常工作。我得到的最常见的例外是PInvoke正在取消堆栈的平衡,因为函数调用与原型不匹配。
I've seen examples using string or StringBuilder, or IntPtr as replacements for the char * required by the DLL function prototype, but I've not been able to get any of them to work. The most common exception I get is that PInvoke is unbalancing the stack because the function call does not match the prototype.
有一个简单的解决方案吗?
Is there a simple solution to this?
推荐答案
更新外部函数的P / Invoke声明如下:
Update your P/Invoke declaration of your external function as such:
[DllImport("dork.dll")]
public static extern int CopyFunc([MarshalAs( UnmanagedType.LPStr )]string a, [MarshalAs( UnmanagedType.LPStr )] string b);
int GetFuncVal(string src, string dest)
{
return(CopyFunc(dest,src));
}
这篇关于从C#字符串将char *传递给C DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!