tags:

views:

321

answers:

2

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.

A: 

Try

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

and use Marshal.GetObjectForNativeVariant with the return value to get a .NET object.

liggett78
+6  A: 

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.

Rob Kennedy