在Delphi中使用C ++类 [英] Using C++ Classes in Delphi

查看:124
本文介绍了在Delphi中使用C ++类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Delphi中使用C ++类?我正在尝试通过抽象类使用它。但是它不能按预期工作,我从 Age(); 中得到了奇怪的数字。

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


推荐答案

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

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.

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

What you need to do, to interop between C++ and Delp 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

这篇关于在Delphi中使用C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆