Calling C++ member functions with the thiscall convention
-
10-10-2019 - |
Question
I have an application written in C++ that loads my DLL that is written in Delphi. The application calls an exported function of the DLL and passes it a pointer to an object of a class that has several member functions that I want to call from my Delphi DLL. I have written a Delphi class equivalent of the C++ class:
CClass = class
procedure A(param : Integer); virtual; abstract;
procedure B; virtual; abstract;
end
and the C++ class looks the same
class CClass {
public:
virtual void A(int) = 0;
virtual void B() = 0;
};
The member functions use the thiscall calling convention which does not have a Delphi equivalent. This probably means I need to use assembly. I have tried:
function exported_procedure(ptr : CClass) : Integer; cdecl;
begin
asm
push ebx;
push esi;
mov ecx, ptr;
push 4;
call CClass.A;
pop esi;
pop ebx;
end;
Result := 0;
end
But I get a segmentation fault when the application calls this function. How do I properly call the member function?
Solution
The asm looks fine, that's how we call a thiscall interface. But this is a class. I don't think there's any reason to assume CClass.A actually calls void A(int). You'd have to figure out the correct offset. Having a Delphi class won't help I think: you should find out the offsets in C++, add that offset to ptr and call that address.