Using C++ Classes in Delphi

人走茶凉 提交于 2019-12-22 17:43:21

问题


How can I use a C++ class in Delphi? I am trying to use it through an abstract class. However it doesn't work as expected I get weird numbers from Age();.

Delphi:

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;
}

回答1:


You can't interop with C++ classes from Delphi. In fact, you can only reasonably do it from C++ if you use the same compiler and runtime.

What you need to do, to interop between C++ and Delphi, is to expose your C++ classes using COM. If COM is not an option then flattening the class is the alternative. Rudy Velthuis covers these options here: http://rvelthuis.de/articles/articles-cppobjs.html



来源:https://stackoverflow.com/questions/27666919/using-c-classes-in-delphi

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