This is what I came up with:
The unmanaged function:
extern "C" __declspec(dllexport) char* callme(const char * sing) {
char buf[10];
sprintf(buf,"hey %s",sing);
return buf;
}
The calling function:
class Program
{
[DllImport("testnonclr.dll", CharSet = CharSet.Auto, CallingConvention =
CallingConvention.Cdecl)]
public static extern IntPtr callme([In,MarshalAs(UnmanagedType.LPStr)]
string sing);
static void Main(string[] args) {
Console.Write( Marshal.PtrToStringAuto (callme("baby") ));
Console.ReadLine();
}
}
The result: a bunch of gibberish
Ok, thanks to the help of some users and more digging, this is what I ended up doing:
extern "C" {
__declspec(dllexport) char* __stdcall callme(const char * sing)
{
static char *buf=NULL;
char fubb[10];
sprintf(fubb,"hey %s",sing);
ULONG usize=strlen(fubb)+sizeof(char);
buf=(char *)::GlobalAlloc (GMEM_FIXED,usize);
strcpy(buf,fubb);
return buf;
}
}
and C#:
class Program
{
[DllImport("testnonclr.dll", CharSet = CharSet.Unicode, CallingConvention = C
CallingConvention.StdCall )]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string callme([In, MarshalAs(UnmanagedType.LPStr)] string sing);
static void Main(string[] args)
{
string rrr = callme("baby");
Console.WriteLine(rrr);
Console.ReadLine();
}
}