我一直在学习将非托管DLL导入编组到C#中...而且我遇到了一些我不太了解的东西.
在Delphi中,有一个函数Result := NewStr(PChar(somestring))从a 返回Procedure SomeFunc() : PChar; Stdcall;
根据我的理解,NewStr只在本地堆上分配一个缓冲区...而SomeFunc正在返回一个指向它的指针.
在.NET 4.0(客户端配置文件)中,通过C#我可以使用:
[DllImport("SomeDelphi.dll", EntryPoint = "SomeFunc", CallingConvention = CallingConvention.StdCall)]
public static extern String SomeFunc(uint ObjID);
Run Code Online (Sandbox Code Playgroud)
这在Windows 7 .NET 4.0 Client Profile中很有效(或者正如David所说,"似乎工作").在Windows 8中,它具有不可预测的行为,这使我走上了这条道路.
所以我决定在.NET 4.5中尝试相同的代码并获得Heap损坏错误.好的,现在我知道这不是正确的做事方式.所以我进一步挖掘:
仍在.NET 4.5中
[DllImport("SomeDelphi.dll", EntryPoint = "SomeFunc", CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr _SomeFunc();
public static String SomeFunc()
{
IntPtr pstr = _SomeFunc();
return Marshal.PtrToStringAnsi(pstr);
}
Run Code Online (Sandbox Code Playgroud)
这没有任何障碍.我(新手)担心的是NewStr()已经分配了这个内存,它只是永远坐在那里.我的担忧无效吗?
在.NET 4.0中,我甚至可以这样做,它永远不会抛出异常:
[DllImport("SomeDelphi.dll", EntryPoint = "SomeFunc", CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr _SomeFunc();
public static …Run Code Online (Sandbox Code Playgroud)