从C调用C ++类的成员函数(Visual Studio中) [英] Call C++ class member function from C (Visual Studio)
问题描述
我需要调用从C程序中的C ++成员函数。
我创建的.cpp / .H封装文件在C code,包裹C ++成员函数。
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
i.e.- wrapper.cpp
#include "wrapper.h"
extern "C" {
void wrap_member1()
{
Class::member1();
}
void wrap_member2()
{
Class::member2();
}
}
和wrapper.h:
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();
我的问题是,当我complie:
错误C2061:语法错误:标识符类
My problem is when I complie:
error C2061: syntax error : identifier 'Class'
它指向C ++类的.H声明为错误。同样的结果,如果我没有在包装文件....?
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。我也删除从原型的外部C,并在包装函数接收到错误:
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'
任何意见?
推荐答案
有两个问题:
一,要包括在C头文件中的C ++头文件。这意味着C编译器获得C ++ code。这是什么原因导致您所遇到的错误。作为<一个href=\"http://stackoverflow.com/questions/1479888/call-c-class-member-function-from-c-visual-studio/1479897#1479897\">Reed •科普塞建议,把的#include
在C ++源文件中的C头文件代替。
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.
二,你正在使用的externC
的C头文件。环绕你的语句在 #IFDEF
这样:
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
这将允许该文件是为C和C ++。
This will allow the file to be usable for both C and C++.
这篇关于从C调用C ++类的成员函数(Visual Studio中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!