Nick Hodges
Nick Hodges

Reputation: 17138

Can a C++ Header file with classes be converted to a Delphi unit?

I have a C++ *.h file with three classes in it. The header file is for accessing a DLL. I have almost no C++ knowledge. However, I seem to recall from somewhere that you can't convert a *.h file to a Delphi unit that has classes in it. Is this true?

If it isn't true, and classes in header files aren't a problem, what is the general approach to converting the classes to Delphi?

Upvotes: 8

Views: 1524

Answers (3)

user2253074
user2253074

Reputation: 11

As commented in a previous answer the solution is using SWIG in order to generate the pascal binding. I started the development of the SWIG's pascal module but I had not time to complete it. Basically it works but it lacks all the test cases to be integrated into SWIG.

I used it in my personal projects and I was able to import complex library as GDAL.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613282

C++ classes, just like Delphi classes, are not designed for binary interop.

A Delphi class can only be exported for consumption by other Delphi code, and then only in a package, and only when runtime packages are in use, and only when all modules use the same version of Delphi. In a similar vein, C++ classes can only be imported from a DLL by code compiled with the same tool chain that compiled the DLL.

So, it is not possible for your Delphi code to consume this DLL. As I see it you have the following options:

  1. Persuade the supplier of the DLL to provide an interop friendly interface to the library. For instance, a plain functional C style interface, or a COM interface.
  2. Write an adapter in C++, using the same compiler that was used to build the DLL. That would involve you importing the classes into your wrapper and exposing them to your Delphi code in an interop friendly manner. Again, plain C style interface or COM are the obvious choices.

Upvotes: 8

Mason Wheeler
Mason Wheeler

Reputation: 84590

In the sense of allowing you to use the DLL from Delphi code? Yeah, good luck with that. You know how you can't use Delphi classes in a DLL unless the client code is written in the same version of Delphi and even then it's usually a bad idea due to shared memory management gotchas? C++ poses exactly the same problem, only exponentially worse because there's no standardized ABI and there's all sorts of C++-language screwed-uppedness making problems for you.

The only real way to make it work reliably is with an interface that uses a standard ABI. If you have the source, try making a C interface that wraps the C++ interface. If not, ask the person who wrote the DLL to provide a C interface, and ask whoever made the decision to use this DLL why you're using a 3rd party library with no source available. :P

Upvotes: 3

Related Questions