Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ DLL plugin interface

I'm planning on doing a C++ plugin interface ala How to create some class from dll(constructor in dll)?(с++) but concerns have been raised that if the interface is used to create DLLs via MinGW or Borland and the DLL loader is compiled with MSVC++, there might be problems. Since the only exported function is declared extern "C" I fail to see why it would not work ?

Ideas ?

like image 592
Robert Avatar asked Jan 21 '11 08:01

Robert


1 Answers

If you want to be compatible across compilers (and Release / Debug) and use C++, you need a little more effort.

Basically - you are allowed to pass basic datatypes, and pointer to pure virtual classes. These classes must not contain any data member, their destructor must not be public and they should not have overloaded functions.

Memory must not be allocated in one dll and released in another. This means no exceptions and you need some kind of reference counting or returning mechanism.

All methods inside pure virtual class (aka "Interface") must be marked with a call convention (I'd prefer stdcall).

Dynamic casts are not possible as well, so you might need some functionality in all your interfaces to do the trick (like QueryInterface in COM).

This works because most compiler on win32 try to be COM compatible and solve the same problems in a COM compatible way. For getting the first interface, you need a plain C function that is exported from the dll.

If you just use C functions and C data types, everything will work as well. But then you are limited to C without classes & inheritance.

I hope that helps.


Name mangling is not a problem:

1st: if you use C functions with C data types, everything is defined, there's no name mangling (exception: in VS with STDCALL, you need to remap the name to the "normal" C name via Linker directive)

2nd: Methods inside classes are not exported and thus not mangled. You call methods via pointer to pure virtual classes (aka "Interfaces"). This uses an offset and no name. You still can't use the destructor, as the position of the destructor inside the vtbl is not fixed as far as I know.


If you pass structs to functions / methods, be sure to fix the alignment. It is not defined across different compilers.

like image 162
Tobias Langner Avatar answered Oct 16 '22 18:10

Tobias Langner