views:

82

answers:

3

I'm relatively new to DLL importing and function binding. Let's say I have a C++ project which is a GUI library written fully in OOP aiming to be used in games.

My game project however is written in Delphi. I now want to bind Delphi functions to the ones in the DLL.

I would know how to do this with simple functions, without classes like in C - but what about OOP?

So in short: Can I bind Delphi functions to the ones in a DLL which consists of compiled C++ classes?

Aren't classes lost during the compilation process?

+2  A: 

Classes aren't necessarily "lost" in compilation, but Delphi (probably) won't know what to do with C++ classes either. It's possible (I haven't checked recently) that Delphi can use/deal with C++ classes compiled with with the Borland/Embarcadero compiler, but it almost certainly won't know how to deal with anything compiled with (for example) gnu or Microsoft.

This sort of thing is why ActiveX controls (and COM in general) are popular -- they let you export a class from a DLL that follows a specification for the binary interface, allowing that class (or those classes) to be used from anything else that knows about ActiveX (and anymore, that includes nearly everything).

Jerry Coffin
A: 

This is tricky, since C++ uses a very different object model than Delphi. Rudy Velthius wrote a pretty good article on how to accomplish it, using two different methods, both of which are kinda ugly.

Mason Wheeler
+3  A: 

I'm still coming to grips with many aspects of C++, but hopefully the following makes some kind of sense.

There are some aspects of C++ that I don't think will translate well via a purely DLL import based mechanism. For example I don't think that you'll be able to support polymorphism or method overloading.

However, that doesn't mean that you can't make use of classes. I think that the easiest way to convey how this might work is a toy example.

//Start with a class definition
class foo
{
  int bar = 0;
  int getBar();
};

// Now create a C API that you can access from Delphi
extern "C" {

void *createFoo()
{
  return new foo();
}

int getBar(void *fooInstance)
{
  foo *fooObj = (foo*)fooInstance;
  return fooObj->getBar();
}

} // end of extern "C"

Then export the extern "C" functions to delphi and use them.

I don't have a compiler handy to test that, and there may be mistakes, however hopefully there is enough there to convey the concept. If there are any gross errors, please let me know and I'll fix it.

torak
Very interesting approach, thanks for the answer!
lamas