【发布时间】:2013-08-25 03:02:12
【问题描述】:
我有一个用 Delphi "a.dll" 编写的第三方 DLL(无源代码)。
这个 DLL 有一个带有这个签名的方法。
function GetAny(pFileName: String): String;
我无法从 c# 进行互操作调用,因为“字符串类型”在 delphi 中具有私有访问权限。
因此,在 delphi 中构建另一个 DLL 来包装该调用。
德尔福。
function GetAny(pFileName: String): String; external 'a.dll'
function GetWrapper(url : PChar) : PChar; stdcall;
begin
Result := PChar(GetAny(url)); // I need avoid this String allocation, is throwing a exception.
end;
C#。
[DllImport("wrapper.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern IntPtr GetWrapper(String url);
在“GetWrapper”内部,我调用了外部“GetAny”,结果正常(在 delphi 中我可以调试),但在我将这个结果返回到 c# 端之前,它抛出了一个异常。
IntPtr test = GetWrapper("a");
String result = Marshal.PtrToStringAnsi(test);
【问题讨论】:
-
将您的 Delphi 包装器更改为接受 char 目标缓冲区的过程。