2

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;
}
15
  • 1
    It looks a little bit odd using prefix I for a normal class. Everyone would expect an interface. And an interface is that what you should use for that Commented Dec 27, 2014 at 12:26
  • 1
    I don't see __stdcall in your C++ code. If you are using only virtual methods and same calling convention on both sides I believe it should work. Commented Dec 27, 2014 at 12:49
  • 1
    @user It would only ever work so long as the compilers happened to lay out the VMT in an identical way. No reason to expect that. That the caller specified the methods in different orders won't help. Commented Dec 27, 2014 at 12:55
  • 1
    I see no reason why it should't work with GCC/FPC. VMT format is identical everywhere though it is never stated explicitely Commented Dec 27, 2014 at 13:06
  • 1
    @John Why are you trying to reinvent COM? Commented Dec 27, 2014 at 13:14

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the mention! The flattening is easier from the C(++) side, the COm option is easier for the Delphi side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.