views:

392

answers:

3

I need to call a C++ member function from a C program.
I created .cpp/.h wrapper files in the C code, wrapping the C++ member functions.

i.e.- 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 complie:
error C2061: syntax error : identifier 'Class'

It points to the .h declaration of the C++ class as an error. Same result as if I did not have the wrapper files....?

P.S. I also removed the "extern "C" " from the prototypes and received an error on the wrapper function:

error C2732: linkage specification contradicts earlier specification for 'wrap_member1'

Any advice?

+2  A: 

You need to include your class in wrapper.cpp:

#include "wrapper.h"
#include "ClassHeaderFile.h" // The header that defines "Class"

extern "C" {

  void wrap_member1()
  {
    Class::member1();
  }

  void wrap_member2()
  {
    Class::member2();
  }
}
Reed Copsey
doesn't seem to change anything. Also, why do I need to include it here if it is included in the wrapper.h that is includded in the wrapper.cpp? just curious...
Tommy
You should _remove_ it from wrapper.h, and add it to wrapper.cpp. Keep in mind that wrapper.h should contain no C++ code if you want it to be usable from C - and `class` is obviously C++ code.
Pavel Minaev
+2  A: 

In your wrapper you must conditionaly compile the extern "C" part, because is a C++ only construct:

wrapper.h:

#ifdef __cplusplus
extern "C" {
#endif

extern void wrap_member1();

#ifdef __cplusplus
}
#endif

In the wrapper.cpp:

extern "C" void wrap_member1()
{
  Class::Member1();
}

In your C module you include only wrapper.h and link to wrapper.obj.

BTW Objective-C is capable of consuming C++, just change the name of your file from *.m to *.mm in XCode.

Remus Rusanu
What does Obj-C have to do with anything?
jalf
The original post had an Objective-C tag
Remus Rusanu
+3  A: 

There are two issues:

One, you are including a C++ header file in a C header file. This means the C compiler gets C++ code. This is what causes the error you are experiencing. As Reed Copsey suggests, put the #include in the C++ source file instead of the C header file.

Two, you are using extern "C" in the C header file. Wrap your statement in an #ifdef as such:

#ifdef __cplusplus
extern "C" {
#endif

/* Functions to export to C namespace */

#ifdef __cplusplus
}
#endif

This will allow the file to be usable for both C and C++.

strager