将char *从C#字符串传递给C DLL

我需要在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#app需要看起来像这样:

 [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作为DLL函数原型所需的char *的替换的示例,但我无法使它们中的任何一个工作。 我得到的最常见的exception是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)); }