Objects in C ++ cannot be directly used in Delphi. in Delphi, they do not have C ++ class declarations and do not know the structure of the passed memory block.
Even translating C ++ classes into Delphi cannot be used directly, because the two languages have different structures for objects.
But the two are the same, that is, the virtual method table. As long as we ensure that the virtual method tables of classes declared on both sides are consistent, we can call the virtual method of the C ++ object in Delphi.
Example:
C ++ has the following classes:
Class ctest {public: Virtual void * _ cdecl opendocument (wchar_t * );};
Note: Because the virtual method table mechanism is used, the method must be declared as a virtual method. In addition, the class call Convention of C ++ is _ thiscall, this is not available in Delphi, so you should change it to _ cdcel (_ stdcall is also acceptable, as long as both sides are consistent)
Then we need to export a function to generate the ctest object.
Extern "C" _ declspec (dllexport) ctest * createtest (void );
OK, C ++ is finished.
Delphi first needs to import the function.
Function createtest (): ttest; cdecl; External 'test. dll ';
The key is what type the function returns. In C ++, The ctest Object Pointer is returned. in Delphi, We need to redeclare this class.
Ttest = Class (tobject) Public Function opendocument (afilename: pwidechar): pointer; virtual; cdecl; abstract; end;
Since the real object is created in C ++, Delphi only needs to map the virtual method table to the table. Therefore, the methods are declared as abstract methods and do not need to be implemented, this class will not be created in Delphi.
After that, you can pass the objects in C ++ to Delphi. in Delphi, you can also call its methods like ordinary objects (of course, these virtual Methods declared ).
It should be noted that the Virtual Methods declared on both sides of the class must be in the same order, and the simple class is guaranteed. However, if there is class inheritance, this is not so guaranteed. People familiar with delphi know that all the classes in Delphi are derived from a base class tobject, And the tobject itself has eight virtual methods. In the above example, we can make a bold guess that the virtual method of the sub-class in Delphi is in front of the table, and the virtual method of the parent class is in the back. This corresponds to C ++.