I'm working on a C++ library that is going to be dynamic loaded (dlopen, dlsym...) in C++ and C programs as a plugin.
C++ programs will use a creator a destroyer functions from the library to call the constructor and destructor respectively. Something like this:
void *creator(void *instance) {
return new MyClass();
}
void destroyer(void *instance) {
MyClass *_instance = static_cast<MyClass*>(instance);
delete _instance;
}
Problem is: It is not that type safe.
Is it possible to be type safe here? (static_cast
, dynamic_cast
, reinterpret_cast
...)
This is important, since I intend to create a C wrapper for every MyClass method. That would allow me to load this library into a C program (something like DBus C porting that may be used with C style or C++ style). So I'd do something like this:
int MyClassAddInts(void *instance, int a, int b) {
MyClass *_instance = static_cast<MyClass*>(instance);
return _instance->addInts(a, b);
}
Please, keep in mind this is just a dummy example.
Thanks very much.
Not really. The whole point of going through a C interface is that you strip all dependence on any C++ ABI, so there's no way you can preserve type information through that in a "natural" fashion.
f it really matters to you, you could rig up some complicated metadata infrastructure to allow for some runtime tests, but you certainly won't get compile-time type-safety out of this.