How can we call "C++" class member functions in 'C" code ?
I have two files .cpp, in which I have defined some classes with member functions and corresponding ".h" files which has included some other helping cpp/h files.
Now I want to call these functionality of CPP files in "C" file. How can I do it?
A member function is declared and defined in the class and called using the object of the class. A member function is declared in the class but defined outside the class and is called using the object of the class.
Calling Class Member Function in C++ Similar to accessing a data member in the class, we can also access the public member functions through the class object using the dot operator (.) . Similarly we can define the getter and setter functions to access private data members, inside or outside the class definition.
C and C++ are two closely related programming languages. Therefore, it may not come as a surprise to you that you can actually mix C and C++ code in a single program. However, this doesn't come automatically when you write your code the normal way.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With