在delphi / pascal中使用C ++接口 [英] Using C++ interface in delphi/pascal
问题描述
我在dll中定义了以下接口:
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();
接口在dll中实现,我可以在C ++中使用它而没有任何问题(我是还定义了 .def
文件,以确保一切正常)。然而,当它在pascal中使用它时我遇到了问题。
以下是我在pascal中尝试使用接口
的方法:
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;
在pascal中使用接口:
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;
一切似乎都很好。调试时, CreateInterface
成功执行, myXYZ
中有一些值。但是当我尝试调用 foo
时出现访问冲突错误。
我注意到我可以从dll中调用不在任何类中的函数但不是那些在类/接口内的东西。
我做错了吗?我怎么能这样做?
我有没有办法在delphi中使用C ++ dll而不改变C ++源代码?
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?
推荐答案
首先,你的Delphi代码有一个从IInterface派生的对象,你的C ++没有。
To start with, your Delphi code has an object derived from IInterface, and your C++ doesn't.
但是,我建议你读这个文章,作者:Rudy Velthuis: -
But, I'd suggest you read this article, by Rudy Velthuis:-
http ://rvelthuis.de/articles/articles-cppobjs.html
基本上,您需要将C ++端实现为COM对象,或者'将您的C ++对象展平为C可调用函数。
Basically, you either need to implement the C++ end as a COM object, or 'flatten' your C++ objects into C callable functions.
这篇关于在delphi / pascal中使用C ++接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!