I tried to compile and link the second example (see below), in the second FAQ in this link in isocpp.org.
Naturally, this works only for non-member functions. If you want to call member functions (incl. 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); /* ... */ }
After several trials, I succeeded executing the example in VS2015. But I'm still not convinced about the declaration extern "C" struct C *p = &c;
that I had to use in other.cpp
(I simply couldn't make the code to work with anything different than this). Note that the C++ compiler emits the following warning for the alluded declaration:
warning C4099: 'C': type name first seen using 'class' now seen using 'struct'
main.c
was compiled with the C compiler and other.cpp
with the C++ compiler.
main.c
/* C code: */
#include <stdio.h>
extern struct C *p;
double call_C_f(struct C* p, int i);
void ccc(struct C* p, int i)
{
double d = call_C_f(p, i);
printf("%f", d);
}
int main()
{
ccc(p, 1);
}
other.cpp
// C++ code:
class C {
public:
virtual double f(int i) { return i; };
} c;
extern "C" struct C *p = &c; // This is the declaration that I'm concerned about
// Is it correct?
extern "C" double call_C_f(C* p, int i) // wrapper function
{
return p->f(i);
}