web analytics

How to call C functions from C++ and vice versa?

Options
@2016-02-01 23:40:41

Calling C++ Functions from C

Name mangling is not desirable when linking C modules with libraries or object files compiled with a C++ compiler. The extern "C" linkage specifier can also be used to prevent mangling of functions that are defined in C++ so that they can be called from C.

// C++ code:

extern "C" void f(int);

void f(int i)
{
 // ...
}

Now f() can be used like this:

/* C code: */

void f(int);

void cc(int i)
{
 f(i);
 /* ... */
}

Naturally, this works only for non-member functions. If you want to call member functions (including virtual functions) from C, you need to provide a simple wrapper. For 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);
}

Now C::f() can be used like this:

/* 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);
 /* ... */
}

If you want to call overloaded functions from C, you must provide wrappers with distinct names for the C code to use. For example:

// C++ code:

void f(int);
void f(double);

extern "C" void f_i(int i) { f(i); }
extern "C" void f_d(double d) { f(d); }

Now the f() functions can be used like this:
/* C code: */

void f_i(int);
void f_d(double);

void cccc(int i,double d)
{
 f_i(i);
 f_d(d);
 /* ... */
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com