Calling “C++” class member function from “C” code

C has no thiscall notion. The C calling convention doesn’t allow directly calling C++ object member functions.

Therefor, you need to supply a wrapper API around your C++ object, one that takes the this pointer explicitly, instead of implicitly.

Example:

// C.hpp
// uses C++ calling convention
class C {
public:
   bool foo( int arg );
};

C wrapper API:

// api.h
// uses C calling convention
#ifdef __cplusplus
extern "C" {
#endif

void* C_Create();
void C_Destroy( void* thisC );
bool C_foo( void* thisC, int arg );

#ifdef __cplusplus
}
#endif

Your API would be implemented in C++:

#include "api.h"
#include "C.hpp"

void* C_Create() { return new C(); }
void C_Destroy( void* thisC ) {
   delete static_cast<C*>(thisC);
}
bool C_foo( void* thisC, int arg ) {
   return static_cast<C*>(thisC)->foo( arg );
}

There is a lot of great documentation out there, too. The first one I bumped into can be found here.

Leave a Comment