atoMerz
atoMerz

Reputation: 7672

Using C++ interface in delphi/pascal

I have the following interface defined in a dll:

class TestInterface
{
   public: int foo(int)=0;
};

And the following functions let's me create objects of this type:

extern "C" declspec(dllexport) TestInterface* __stdcall CreateInterface();

The interface is implemented in the dll and I can use it in C++ without any problems (I've also defined the .def file to make sure everything works correctly). However when it comes to using it in pascal I have problems.
Here's how I'm trying to use the Interface in pascal:

type
  myinterface = interface(IInterface)
    function foo(param1: Integer): Integer;
  end;

TMyInterface = ^myinterface;
pCreateInterface = function: TMyInterface; stdcall;

var
  CreateInterface: pCreateInterface;

Using interface in pascal:

function init()
begin
  DllHandle := LoadLibrary(DLLPath);
  if DllHandle <> 0 then
  begin
    @CreateInterface := GetProcAddress(DllHandle, 'CreateInterface');
    if (@GetXYZ <> nil) then
    begin
      dllInitialized := true;
      myXYZ := CreateInterface();
      myXYZ.foo(1); // Access violation error here
    end;
  end;
end;

Everything seems to be good. When debugging, CreateInterface executes successfully and there is some value in myXYZ. But when I try to call foo I get access violation error.
I've noticed I can call functions that are not within any class from a dll but not those that are inside class/interface.
Am I doing something wrong? How can I do this?
Is there a way I can use a C++ dll in delphi without changing C++ source?

Upvotes: 0

Views: 2589

Answers (1)

Roddy
Roddy

Reputation: 68033

To start with, your Delphi code has an object derived from IInterface, and your C++ doesn't.

But, I'd suggest you read this article, by Rudy Velthuis:-

http://rvelthuis.de/articles/articles-cppobjs.html

Basically, you either need to implement the C++ end as a COM object, or 'flatten' your C++ objects into C callable functions.

Upvotes: 4

Related Questions