问题
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