delphi - 在 Delphi 中使用 C++ 类

标签 delphi delphi-xe7

如何在 Delphi 中使用 C++ 类?我试图通过抽象类使用它。然而它并没有按预期工作,我从 Age(); 得到奇怪的数字。

德尔福:

program Test;

{$APPTYPE CONSOLE}

type
  IPerson = class
    function Age(): Integer; overload; virtual; stdcall; abstract;
    procedure Age(const Value: Integer); overload; virtual; stdcall; abstract;
  end;

const
  DLL = 'Interface.DLL';

procedure FreePerson(const Person: IPerson); external DLL;
function CreatePerson(): IPerson; external DLL;

var
  Person: IPerson;
  I: Integer;
begin
  Person := CreatePerson;
  Person.Age(10);
  I := Person.Age(); // I is not 10?

end.

C++:

extern "C" class _declspec(dllexport) IPerson
{
    virtual void Age(const int Value) = 0;
    virtual int Age() = 0;
};


class Person: public IPerson
{
private:
    int FAge;
public:
    void Age(const int Value){FAge = Value;};
    int Age(){return FAge;};
    Person(){ FAge = 0; };
    ~Person(){};
};


extern "C" _declspec(dllexport) IPerson* CreatePerson()
{
    return new Person;
}

extern "C" _declspec(dllexport) void FreePerson(Person** obj)
{
    delete obj;
}

最佳答案

您无法与 Delphi 中的 C++ 类进行互操作。事实上,如果您使用相同的编译器和运行时,您只能从 C++ 合理地做到这一点。

要在 C++ 和 Delphi 之间进行互操作,您需要做的是使用 COM 公开您的 C++ 类。如果 COM 不是一个选项,那么扁平化类是另一种选择。 Rudy Velthuis 在这里介绍了这些选项:http://rvelthuis.de/articles/articles-cppobjs.html

关于delphi - 在 Delphi 中使用 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27666919/

相关文章:

delphi - 如何识别哪个控件是Sender?

sql-server - 编写 CLR 存储过程

php - 使用 php 和 delphi 的简单套接字?

delphi - 我可以检测窗口是否部分隐藏吗?

delphi - FastMM 在没有 FullDebugMode 的情况下记录到文件

delphi - 如何使 TProgressColumn 与 LiveBindings 和数据集一起使用时工作

delphi - 处理大量行时,TMemo 速度慢得令人痛苦

delphi - Free Pascal 到 Delphi 的转换 - Generic T 默认参数

delphi - 如何将 TObject 转换为 TObjectList<T>?

c - Delphi 中通过引用传递的指针(从 DLL 导入函数)