Here's the native (Delphi 7) function:
function Foo(const PAnsiChar input) : PAnsiChar; stdcall; export;
var
s : string;
begin
s := SomeInternalMethod(input);
Result := PAnsiChar(s);
end;
I need to call this from C#, but the name of the dll is not known at compile time - so I must use LoadLibrary to get to it.
This is what my C# code looks like so far:
[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);
Now, this actually works - at least, the delphi code receives the string correctly, and the C# code receives the output string.
However, I've noticed some weirdness when debugging the delphi code when it's called from the C# code - the debugger skips lines when it shouldn't..
And I'm concerned that I'm leaking memory - is anyone cleaning up those PChars?
Can anyone give me some feedback / advice on how this should be done?