我需要从 C 程序调用 C++ 成员函数。
我在 C 代码中创建了 .cpp/.h 包装器文件,包装了 C++ 成员函数。
即-wrapper.cpp
#include "wrapper.h"
extern "C" {
void wrap_member1()
{
Class::member1();
}
void wrap_member2()
{
Class::member2();
}
}
和包装器.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();
我的问题是当我编译时:
错误 C2061:语法错误:标识符“Class”
它指向 C++ 类的 .h 声明作为错误。结果与我没有包装文件一样......?
附:我还从原型中删除了“extern“C””,并在包装函数上收到了错误:
error C2732: linkage specification contradicts earlier specification for 'wrap_member1'
有什么建议吗?
有两个问题:
第一,您在 C 头文件中包含 C++ 头文件。这意味着 C 编译器获得 C++ 代码。这就是导致您遇到错误的原因。作为里德·科普西 https://stackoverflow.com/questions/1479888/call-c-class-member-function-from-c-visual-studio/1479897#1479897建议,把#include
在 C++ 源文件中而不是 C 头文件中。
二、你正在使用extern "C"
在C头文件中。将您的陈述包含在#ifdef
像这样:
#ifdef __cplusplus
extern "C" {
#endif
/* Functions to export to C namespace */
#ifdef __cplusplus
}
#endif
这将使该文件可用于 C 和 C++。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)