我一直在跟随this guide学习如何从C中调用C++对象的成员函数。据我所知,C代码应该将该类解释为同名的结构,并且每当它想要通过该类的对象调用函数时,它都应该使用中间回调函数。标题看起来像这样:
// CInterface.h
#ifdef __cplusplus
...
class CInterface
{
public:
...
void OnMessage(U8* bytes); // I want to call this function from C.
private:
...
};
#else
typedef
struct CInterface
CInterface;
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__STDC__) || defined(__cplusplus)
//extern void c_function(CInterface*); /* ANSI C prototypes (shouldn't be needed) */
extern CInterface* cpp_callback_function(CInterface* self, unsigned char * bytes);
#else
//extern void c_function(); /* K&R style (shouldn't be needed) */
extern CInterface* cpp_callback_function(unsigned char * bytes);
#endif
#ifdef __cplusplus
}
#endif现在失败的C代码看起来像这样: // main.c #include "CInterface.h“
int main(int argc, char* argv[])
{
void* ptr;
int *i = ptr; // Code that only compiles with a C compiler
CInterface cinterface; // This should declare a struct
}错误是: error C2079:'CInterface‘使用未定义的结构'cinterface’。
这听起来像是将头文件作为c++代码读取,因为结构没有定义,但main.c是由C根据Visual Studio编译的(我还通过添加一些C特定的代码对此进行了仔细检查)。但是,如果我像这样添加括号:
CInterface cinterface();代码编译了,这对我来说毫无意义,因为它现在是一个不应该在C中工作的对象。
回调函数在第三个文件CInterface.cpp中实现,该文件充当“中间层”。
所以问题是我如何解决这个错误消息,或者如果我把整个方法都搞错了。这是我第一次混合使用C/C++代码,而且我对这两种语言都比较陌生。
发布于 2012-10-03 00:04:37
在您的示例中,仅为C++定义了CInterface。如果您仔细查看所链接的示例,您会注意到Fred类也是如此。
在C语言中,你只能传递指向CInterface的指针,而且你必须依赖于使用C语言定义的C++函数来实际操作CInterface实例。
否则,您可以将struct定义为在C和C++之间传递数据的一种方式。在C++中使用时,只需确保其定义声明为extern "C":
#ifdef __cplusplus
extern "C" {
#endif
struct CandCPlusPlus {
// ...
};
#ifdef __cplusplus
}
#endifhttps://stackoverflow.com/questions/12693768
复制相似问题