I am trying to use some software which has been written in C++ in a separate C program.
I have compiled the necessary components within a .lib file, and included some C code using
#ifdef __cplusplus
extern "C" {
#endif
This code sort of wraps up the C++ object method calls within C callable functions. The objects are declared in file scope, and pointers to the objects are retreived initially and then later used to reference which object to call the method on. For example:
const void *GetHandle() {
return (void *) &obj;
}
And then to call a method:
int GetInt(const void *handle) {
Object *temp = (Object *) handle;
return temp->getInt();
}
Is this a valid solution to the problem? At the moment, with just the GetHandle() methods in my C program, I get errors saying “error C2099: initializer is not a constant” when I try to assign their return values to some const void * variables.
EDIT
Fixed the problem. My ignorance of standard C bears itself here. I am used to Microchip C30 for dsPIC, which is a little different.
I was trying to both declare and initialize the pointers outside of any function. I did have them set as const but that’s not really necessary, so I now just declare outside and then initialize in an init function. I also put extern “C” in front of all the functions in the cpp file, and it all compiles now. So, thanks to everyone for the help!
This is a valid solution.
You might want to check the
constness of your argument/return values/casts more carefully though.For example, if the object itself is not
const, thenGetHandleshould returnvoid *, notconst void *. Same way, ifgetIntis aconstfunction, thenGetIntcorrectly gets aconst void *. However, it should also cast it toconst Object *, notObject *.For further diagnosis, you should provide the exact line you get the
initializer is not a constanterror (and the context where the function is called). My guess is that the error is related to some other part of your code, using these incorrectly cast values.