Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass char * to C DLL from C# string

Tags:

c++

c#

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:

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?

like image 468
buzzard51 Avatar asked Oct 11 '16 21:10

buzzard51


1 Answers

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));
}
like image 100
BugsFree Avatar answered Oct 05 '22 23:10

BugsFree