Using C++ interface in delphi/pascal

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-03 05:56:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14731390/using-c-interface-in-delphi-pascal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!