【发布时间】:2009-11-09 23:56:35
【问题描述】:
这是本机 (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 代码时,我在调试它时发现了一些奇怪的地方 - 调试器在不应该的时候跳过了行。
而且我担心我会泄漏内存 - 有人清理这些 PChar 吗?
谁能给我一些反馈/建议,告诉我应该怎么做?
【问题讨论】:
-
我唯一一次看到调试器不应该跳过行是编译的代码与源代码不匹配。您确定要绑定到正确版本的程序集吗?
标签: c# .net delphi pinvoke delphi-7