如何从C调用C++函数?

Che*_*Boy 4 c c++

我有一个标题声明函数,这些函数将指向C++对象的指针作为参数.该实现是一个单独的C++文件.如何在C中包含此标头并使用C中的函数,即使参数需要是C++对象指针?

Omn*_*ous 6

不幸的是,我的第一次尝试回答错误的问题....

对于你问过的问题......

正如有人指出的那样,你可以绕过去void *.这也是我也会推荐的.就C而言,指向C++对象的指针应该是完全不透明的.

如果C++函数extern "C"位于全局名称空间中,也可以标记它们.这是一个例子:

myfunc.hpp:

#ifdef __cplusplus
extern "C" {
#endif

extern int myfunction(int, void *ob);

#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

myfunc.cpp:

#include "myfunc.hpp"

void myfunction(int x, void *vobptr)
{
    ClassType *ob = static_cast<ClassType *>(vobptr);
}
Run Code Online (Sandbox Code Playgroud)

afoofile.c

#include "myfunc.hpp"

void frobble(int x, void *opaque_classtype_ptr) {
    myfunction(x, opaque_classtype_ptr);
    /* do stuff with buf */
}
Run Code Online (Sandbox Code Playgroud)

另一个选择是typedef在C中创造性地使用s 做基本相同的事情.这个,恕我直言,非常难看,但无论如何这里是一个例子:

myfunc.hpp:

#ifdef __cplusplus
extern "C" {
#else
typedef void ClassType;  /* This is incredibly ugly. */
#endif

extern int myfunction(int, ClassType *ob);

#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

myfunc.cpp:

#include "myfunc.hpp"

void myfunction(int x, ClassType *ob)
{
    // Do stuff with ob
}
Run Code Online (Sandbox Code Playgroud)

afoofile.c

#include "myfunc.hpp"

void frobble(int x, ClassType *opaque_classtype_ptr) {
    myfunction(x, opaque_classtype_ptr);
    /* do stuff with buf */
}
Run Code Online (Sandbox Code Playgroud)