Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling "C++" class member function from "C" code

Tags:

c++

c

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?

like image 426
Priyanshu Avatar asked Aug 27 '10 10:08

Priyanshu


People also ask

How do you call a member of a class function?

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.

How do you call a class member function in C++?

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.

Can you mix C and C++ code?

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.


1 Answers

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.

like image 93
xtofl Avatar answered Oct 17 '22 16:10

xtofl