user3235770 user3235770 - 1 month ago 17
C# Question

pass char * to C DLL from C# string

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:

The C DLL:

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


the C# app needs to look something like this:

[DllImport("dork.dll")]
public static extern int CopyFunc(string a, string b);

int GetFuncVal(string src, string dest)
{
return(CopyFunc(dest,src));
}


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?

Answer

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