If you want code that can be called from C and also called from C++ in a C++ friendly class, your best bet would be to write your code in C and create a C++ wrapper class that calls into the C code. Just include the appropriate C struct as a member of your C++ class and delegate the class methods to C functions.
Code:
#if defined(__cplusplus)
class A
{
private:
struct A_c;
public:
A( )
{
A_create(&A_c); /* Delegate to C create function. */
}
~A( )
{
A_destory(&A_c);
}
int Amethod1( int params1 )
{
return A_Amethod1(&A_c, params1);
}
long Amethod2( int params2 )
{
return A_Amethod2(&A_c, params2);
}
};
#endif /* defined (__cplusplus)
The other alternative is to write your code in C++ and create a wrapper so it can be accessed from C. The disadvantage to this approach is that your code will need a C++ compiler to be compiled. With the C code/C++ wrapper solution, you can use defines so that the C++ wrapper is not compiled on a C compiler. The advantage is that you can leverage the benefits of C++ in your code.
Here is an example of a wrapper that enables a C++ class to be called from C code.
Code:
/* Create a handle type for your class. */
typedef void* CLS_HANDLE;
extern "C" void A_create(CLS_HANDLE* ppHandle)
{
A* temp = new A;
*pHandle = (CLS_HANDLE) temp;
}
extern "C" int A_Amethod1(CLS_HANDLE pHandle, params1 )
{
A* temp = (A*) pHandle;
return temp->Amethod1(params1);
}
extern "C" int A_Amethod2(CLS_HANDLE pHandle, params2 )
{
A* temp = (A*) pHandle;
return temp->Amethod2(params2);
}
extern "C" void A_destroy(CLS_HANDLE pHandle)
{
A* temp = (A*) pHandle;
delete temp;
}