I have a question regarding wrapping/linking protocols between C and C++. I'm working on existing C++ code that I have to wrap into a C object file for use in a different environment, namely I have a main C program that has to be able to link to the C++ generated .o effectively. Also, I have a C header file that specifies the interface struct between the old environment and the new one that my C main() will have to utilize. I've created a .cc, which will generate the .o, that includes other required C++ headers and the C header interface, specifying C linkage for the interface.h with 'extern "C"'.
In order to do this I created wrapper functions to virtual C++ member functions (in other .hh's) by passing void* as a parameter to the wrapper, dereferencing the pointer and calling the member function within the wrapper, and then specifying C linkage as above. I need to create a 'constructor' wrapper function (in my interface.h) that returns a void* to a C++ class instance. With this I can instantiate and then dereference the pointer in my C main, allowing access to C++ class instances; however, because I can't include C++ headers in the interface.h, I can't find a way to declare the instance of a specific C++ class type. Likewise I need to build a 'destructor' wrapper function which will deallocate the instance of this class but I run into the same problem.
My other question is that the existing code has an analogous C++ struct with exactly the same members as the interface.h struct, although it is given in a C++ header. The other .hh's require this C++ type to be passed as function parameters. The only idea I had would be to use static_cast or reinterpret_cast<c++_type>c_type in functions that require the C++ type as a parameter. I am not familiar with the implementation details of these casts and don't know if it will work, granted I can't debug this without the other fix. Is there another way to implement this I am not thinking of?
You shouldn't add the C++ implementation header file to the interface header file. Think of your implementation being C++, but the interface being C. As such, the header file that the C program sees, it pure C. No one needs to know that it uses a C++ implementation. All you need to provide is a set of functions and your handle, in your case void*, but you could expose that as an int.
Take for example, take file handling. There's open, close, read, write, seek, tell, all accessed via a handle. You never see the implementation, just functions and a handle.
You have to decide where this struct lives. Is it an interface record or an implementation detail? If it's an interface record, define it as a C struct in the interface header file; otherwise hide it in the implementation.
Ah yeah it would be an implementation detail so I'll prototype the function in the header and then just define it in my .cc so that the object file I link to the main C program will contain the function definition.