Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling C++ method from C code

Tags:

c++

c

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.

like image 260
Zohar81 Avatar asked Apr 18 '16 10:04

Zohar81


1 Answers

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;
like image 133
Bryan Chen Avatar answered Sep 21 '22 21:09

Bryan Chen