这是本机(Delphi 7)功能:
function Foo(const PAnsiChar input) : PAnsiChar; stdcall; export;
var
s : string;
begin
s := SomeInternalMethod(input);
Result := PAnsiChar(s);
end;
我需要从 C# 调用它,但在编译时不知道 dll 的名称 - 所以我必须使用 LoadLibrary 来获取它。
到目前为止,这是我的 C# 代码的样子:
[DllImport("kernel32.dll")]
public extern static IntPtr LoadLibrary(String lpFileName);
[DllImport("kernel32.dll")]
public extern static IntPtr GetProcAddress(IntPtr handle, string funcName);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate string FooFunction(string input);
...
IntPtr dllHandle = LoadLibrary(dllName);
IntPtr fooProcAddr = GetProcAddress(dllHandle, "Foo");
FooFunction foo = (FooFunction)Marshal.GetDelegateForFunctionPointer(
fooProcAddr, typeof(FooFuncion)
);
string output = foo(myInputString);
现在,这确实有效 - 至少,delphi 代码正确接收字符串,而 C# 代码接收输出字符串。
但是,当从 C# 代码调用 delphi 代码时,我注意到一些奇怪的地方——调试器在不应该的时候跳过了行。
而且我担心我正在泄漏内存 - 有人清理那些 PChars 吗?
谁能给我一些关于如何做到这一点的反馈/建议?