从c#字符串传递char *到C DLL

pass char * to C DLL from C# string

本文关键字:DLL char 字符串      更新时间:2023-10-16

我需要在c#应用程序的DLL中使用C函数库。我在使用char *参数调用DLL函数时遇到麻烦:

C DLL:

extern "C" __declspec(dllexport) int CopyFunc(char *, char *);
int CopyFunc(char *dest, char *src)
{
    strcpy(dest, src);
    return(strlen(src));
}

c#应用程序需要看起来像这样:

[DllImport("dork.dll")]
public static extern int CopyFunc(string dst, string src);
int GetFuncVal(string source, string dest)
{
    return(CopyFunc(dest,source));
}

我见过使用字符串或StringBuilder或IntPtr作为DLL函数原型所需的char *的替代品的例子,但我没能让它们中的任何一个工作。我得到的最常见的异常是PInvoke使堆栈不平衡,因为函数调用与原型不匹配。

有一个简单的解决方案吗?

更新外部函数的p/Invoke声明:

[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));
}