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 *dest, char *src)
{
strcpy(dest, src);
return(strlen(src));
}
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));
}
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?
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With