problem mixing c and c++
i need to build a c++ project that exports functions to c project this is my c++ class :
** MyCppClass.h **
class MyCppClass
{
public:
static void MyCppMethod()
}
** MyCppClass.cpp **
void MyCppClass::MyCppMethod(){}
*now i need to create an interface for the Method MyCppMethod (static).
i did that : ** MyExport.h**
#define Export __declspec(dllexport)
extern "C" void Export MyCppMethodWrapper();
** MtExport.cpp**
#include "MyCppClass.h"
#include "MyExport.h"
void MyCppMethodWrapper() { MyCppClass::MyCppMethod();}
thats it !
now the C part (different project) i linked the project with MyExport.lib
** program.c**#include "MyExport.h" ->does not compile because of the extern "C"
int main()
{
MyCppMethodWrapper();
}
if i do not add the line : #include "MyExport.h"
at program.c the program compiles and work fine but i need to provide an header for the exports (the client needs the header) and i want to make the program use that header. how can i resolve that ???
thanks for your a开发者_StackOverflownswers
you can easily conditionally define the extern if that is what you want to do as such:
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C
#endif
And then:
EXTERN_C Export MyCppMethodWrapper();
Normally you'd do this the other way around, call C functions in a C++ program, which is what extern "C"
is good for. It doesn't help you in this case.
That you can maybe do is find the name of you static method in the dll, write some extern ...
statement in your C code and then call the static method.
Note that names in a C++ program are mangled, i.e. the names in the object file/library contain information about the class a method belongs to and the type of its parameters. There are tools to demangle names in the Linux world, but I don't know what is available in the MS Windows world, presumably something.
My general advice is to think again if you have to do this at all.
Short answer is: you can use C from C++, but not the other way around!
If you want to use C++ from C, you need to create a thin wrapper, with pure-C functions (i.e. with extern "C" { ... }
used only if compiled in C++ (as this statement are, obviously, not valid in C) and use, from C the functions. This should look something like:
#ifdef __cplusplus // defined at least by G++, I don't know for other compilers
extern "C" {
#endif
// ... function definitions here
#ifdef __cplusplus
}
#endif
As well as brainiac's answer you need to use dllimport in program.c
/* declare function directly */
extern "C" void __declspec(dllimport) MyCppMethodWrapper();
int main()
{
MyCppMethodWrapper();
}
If you want to use the same header you need to use a brainiac's answer and an extra #ifdef
for the __declspec(dllexport)
#ifdef MYDLL
#define Export __declspec(dllexport)
#else
#define Export __declspec(dllimport)
#endif
EXTERN_C void Export MyCppMethodWrapper();
Then you add a /D MYDLL to the build flags of your dll project.
精彩评论