Given the following C++ code,
#ifdef __cplusplus
extern "C" {
#endif
struct foo {
void getNum() {
}
};
#ifdef __cplusplus
}
#endif
int main (int argc, char * const argv[]) {
return 0 ;
}
Is开发者_Python百科 it possible to call getNum()
from C?
No, since getNum
is a member function, which C doesn't have.
A possible solution to that problem is to write a C++ function to return a foo
instance as a foo*
(where foo
is changed to be an empty struct) to C (I assume this is binary compiled as C++ to which C is linking), then have a free function in C++ called foo_getNum
or something, which takes a foo*
(whose definition is modified for the C version to be empty) which calls getNum
on it. It wouldn't be type safe though, obviously, (but taking a foo*
even when foo
is empty would be better than void*
- thanks David).
The extern "C"
has no effect on the member function: getNum()
has C++ language linkage.
The C++ Language Standard states (C++03 §7.5/4):
A C language linkage is ignored for the names of class members and the member function type of class member functions.
So, no, you cannot call this function directly from a C program (though, as others have said, you can't compile that code as C anyway because C does not have member functions). It is of course conceivable that some implementations might allow you to call this function from a C program via some implementation-specific method.
You can't call that member function from C in a portable way. You need to expose your C++ interface by flattening it.
The code you gave will not compile in C mode as C compiler doesn't support functions in struct. However you can create a function in C++ which can call this and link it with C linkage. Create 2 files main.c and abc.cpp
Code for main.c
extern "C" void getNumCaller();
int main ()
{
getNumCaller();
return 0;
}
Code for abc.cpp
#include <iostream>
struct foo {
void getNum() {
std::cout << "calling getNum" << std::endl;
}
};
extern "C" void getNumCaller()
{
struct foo abc;
abc.getNum();
}
Compile the code :
g++ -o abc abc.cpp main.c
and you will get output:
calling getNum
精彩评论