web analytics
How to call C functions from C++ and vice versa? Options
davegate
Posted: Monday, February 1, 2016 11:40:41 PM

Rank:Advanced Member
Groups: Member
Joined: 12/14/2015
Posts: 182
Points: 894

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);
 /* ... */
}
Sponsor
Posted: Monday, February 1, 2016 11:40:41 PM
Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2018 Digcode.com. All rights reserved.