不幸的是,我的第一次尝试回答了错误的问题....
对于你提出的问题...
正如有人指出的那样,您可以绕过void *'s。这也是我要推荐的。就 C 而言,指向 C++ 对象的指针应该是完全不透明的。
如果 C++ 函数位于全局命名空间中,它们也可以标记为 extern "C"。这是一个例子:
myfunc.hpp:
#ifdef __cplusplus
extern "C" {
#endif
extern int myfunction(int, void *ob);
#ifdef __cplusplus
}
#endif
myfunc.cpp:
#include "myfunc.hpp"
void myfunction(int x, void *vobptr)
{
ClassType *ob = static_cast<ClassType *>(vobptr);
}
afoofile.c
#include "myfunc.hpp"
void frobble(int x, void *opaque_classtype_ptr) {
myfunction(x, opaque_classtype_ptr);
/* do stuff with buf */
}
另一种选择是在 C 中创造性地使用 typedefs 来做基本相同的事情。恕我直言,这很丑陋,但无论如何这里有一个例子:
myfunc.hpp:
#ifdef __cplusplus
extern "C" {
#else
typedef void ClassType; /* This is incredibly ugly. */
#endif
extern int myfunction(int, ClassType *ob);
#ifdef __cplusplus
}
#endif
myfunc.cpp:
#include "myfunc.hpp"
void myfunction(int x, ClassType *ob)
{
// Do stuff with ob
}
afoofile.c
#include "myfunc.hpp"
void frobble(int x, ClassType *opaque_classtype_ptr) {
myfunction(x, opaque_classtype_ptr);
/* do stuff with buf */
}