I need to call some C++ code from Delphi. The C++ code needs to be able to callback into the Delphi code in return. The example shown here Calling a callback function in Delphi from a C++ DLL works perfectly well. However, instead of passing to the C++ a single Delphi function as a callback, I would like to pass a Delphi object implementing an interface.
Edit: By interface I am referring to the C++ terminology, which is a class with pure virtual functions. This is not necessarily a type defined with the Delphi interface keyword. In other words, the following class defines an interface I would like to call from C++:
ICallable = class
procedure callMe stdcall; virtual; abstract;
procedure CallMeAgain stdcall; virtual; abstract;
end;
The ICallable interface would in turn be implemented in Delphi as follows:
MyCallable = class(ICallable)
procedure callMe override;
procedure callMeAgain override;
end;
procedure MyCallable.callMe
begin
WriteLine('I was called');
end;
procedure MyCallable.callMeAgain
begin
WriteLine('I was called again');
end;
On the C++ side, which is compiled as a DLL, I want to define the ICallable interface as follows:
class ICallable{
public:
virtual void callMe()=0;
virtual void callMeAgain()=0;
}
And export the following DLL function so that it can be called by Delphi:
#define DllExport extern "C" __declspec( dllexport )
DLLExport bool Callback(ICallable* callable){
callable->callMe();
callable->callMeAgain();
return true;
}
And finally back in Delphi:
function Callback(myCallable: ICallable) : Boolean cdecl; external 'dllname'
Question:
- This can only work if C++ and Delphi implement their virtual method tables in the same way. Is this the case?