I am using the "Unmanaged Exports" library to export functions from a c# class-library. For basic functions with easy signatures this works pretty good. Now I want to export a C# object that my Delphi application wants to work with. The following code compiles:
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)]
public class Sample
{
public string Text
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
[return: MarshalAs(UnmanagedType.BStr)]
public string TestMethod()
{
return Text + "...";
}
}
static class UnmanagedExports
{
[DllExport(CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.IDispatch)]
static Object CreateSampleInstance()
{
try
{
return new Sample { Text = "xy" };
}
catch (Exception ex)
{
return null;
}
}
}
In my Delphi application I want to load the dll via the following code:
function CreateSampleInstance(): IDispatch; stdcall; external 'UnmanagedExports.dll';
procedure TForm3.Button2Click(Sender: TObject);
var
disp: IDispatch;
variant: OleVariant;
begin
CoInitialize(0);
disp := CreateSampleInstance();
variant := disp;
ShowMessage(variant.TestMethod());
end;
I get a null-pointer exception in my Delphi-Code. There must be something wrong with my signatures. Anybody has an idea how to get this working?