【发布时间】:2014-12-14 10:40:39
【问题描述】:
这是我想出的:
非托管函数:
extern "C" __declspec(dllexport) char* callme(const char * sing) {
char buf[10];
sprintf(buf,"hey %s",sing);
return buf;
}
调用函数:
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();
}
}
结果:一堆乱码
好的,感谢一些用户的帮助和更多的挖掘,这就是我最终做的:
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;
}
}
和 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();
}
}
【问题讨论】:
-
我会先学习C,然后尝试P/Ivoke。
-
我知道 C 内存分配的来龙去脉,但在同一个文件中的任何人都知道。
标签: c# c pinvoke marshalling