Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a delphi DLL method from C# Code

Tags:

c#

.net

dll

delphi

I am trying to call a Delphi function from C# ASP.NET code. The function's declaration looks like this:

function SomeFunction(const someString, SomeOtherString: string): OleVariant;

From my C# code I have this code:

[DLLImport(MyDLL.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern object SomeFunction(string someString, string SomeOtherString);

Every time I call this Method and store it as an object, I get a P/Invoke error. I've never called unmanaged code from my C# before, so I'm kind of at a loss.

like image 759
Dan Avatar asked Feb 04 '10 14:02

Dan


1 Answers

You cannot call that DLL function because it uses the Delphi-specific string data type, which has no equivalent in non-Embarcadero products. (Even if your C# code can match the structure of Delphi's string type, you would also need to allocate the memory using the DLL's memory manager, which it almost certainly doesn't export.)

If you have the ability to change the DLL, then make the parameters have type PAnsiChar or PWideChar. (From your C# declaration, it looks like you want PAnsiChar.) That's what the DLL should have used all along.

If you can't change the DLL, then write a wrapper DLL in Delphi or C++ Builder that uses PAnsiChar or PWideChar and then forwards those parameters to the original Delphi DLL. Or complain loudly to the DLL vendor and request a new version that uses types that are more friendly to other languages.

like image 198
Rob Kennedy Avatar answered Oct 03 '22 07:10

Rob Kennedy