Calling a function of a C ++ class class from C (Visual Studio)
I need to call a C ++ member function from a C program. I created .cpp / .h wrapper files in C code by wrapping C ++ member functions.
ie- wrapper.cpp
#include "wrapper.h"
extern "C" {
void wrap_member1()
{
Class::member1();
}
void wrap_member2()
{
Class::member2();
}
}
and wrapper.h:
#include <windows.h>
#include <stdio.h>
#include "../C++ class with members I need to call.h"
extern "C" void wrap_member1();
extern "C" void wrap_member2();
My problem is when I execute:
error C2061: syntax error: id 'Class'
It points to declaring .h of a C ++ class as an error. The same result as if I didn't have the wrapper files ....?
PS I also removed "extern" C "" from prototypes and got an error about the wrapper:
error C2732: linkage specification contradicts earlier specification for 'wrap_member1'
Any advice?
source to share
There are two problems:
First, you include the C ++ header file in the C header file. This means the C compiler gets the C ++ code. This is causing the error you are facing. Like Reed Copsey , put #include
in C ++ source file instead of C header file.
Two, you are using extern "C"
in the C header file. Wrap your statement in #ifdef
as such:
#ifdef __cplusplus
extern "C" {
#endif
/* Functions to export to C namespace */
#ifdef __cplusplus
}
#endif
This will allow the file to be used for both C and C ++.
source to share
In your wrapper, you have to conditionally compile the part extern "C"
, because this is C ++ only:
wrapper.h:
#ifdef __cplusplus
extern "C" {
#endif
extern void wrap_member1();
#ifdef __cplusplus
}
#endif
In wrapper.cpp file:
extern "C" void wrap_member1()
{
Class::Member1();
}
In your C module, you only include wrapper.h and a link to wrapper.obj.
BTW Objective-C is capable of consuming C ++, just change your file name from * .m to * .mm in Xcode.
source to share