I've read the following article here that explain how to call c++ based functions from pure C code.
The method is best explained with the following example :
// C++ code:
class C {
// ...
virtual double f(int);
};
extern "C" double call_C_f(C* p, int i) // wrapper function
{
return p->f(i);
}
/* C code: */
double call_C_f(struct C* p, int i);
void ccc(struct C* p, int i)
{
double d = call_C_f(p,i);
/* ... */
}
However, I fail to understand if where do i define an instance that is pointed by 'p'. notice that in the C code, it is delivered as pointer to opaque struct, and in the C++ code it's assumed to be pointer to valid instance of class C
, but i didn't see where this pointer is being initialized.
p.s. Of course that each code block that relate to different language is compiled with an appropriate compiler, and different object file is created.
You need similar wrapper methods to create and destroy the C++ object.
C++ code:
extern "C" C * create_c()
{
return new C;
}
extern "C" void destroy_c(C *p)
{
delete p;
}
C code:
// forward declarations (better to put those in a header file)
struct C;
struct C * create_c();
double call_C_f(struct C* p, int i);
void destroy_c(struct C *p);
struct C * p = create_c();
double result = call_C_f(p, i);
destroy_c(p);
p = NULL;
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