问题描述
我知道这一点。
这是C ++的调用C函数:
如果我的应用程序是在C ++和我不得不用C编写的一个库,然后我会用调用函数
If my application was in C++ and I had to call functions from a library written in C. Then I would have used
//main.cpp
extern "C" void C_library_function(int x, int y);//prototype
C_library_function(2,4);// directly using it.
这不会裂伤的名称 C_library_function
和连接器会发现在其输入* .lib文件相同的名称和问题解决。
This wouldn't mangle the name C_library_function
and linker would find the same name in its input *.lib files and problem is solved.
调用C ++ C函数???
不过,我在这里延伸的是用C语言编写的大型应用程序,我需要使用的是用C ++库。 C ++的名字改编这里作祟。连接器是抱怨没有得到解决的符号。好吧,我不能使用C ++编译器在我的C项目,因为这就是打破很多其他的东西。何处是路?
But here I'm extending a large application which is written in C and I need to use a library which is written in C++. Name mangling of C++ is causing trouble here. Linker is complaining about the unresolved symbols. Well I cannot use C++ compiler over my C project because thats breaking lot of other stuff. What is the way out?
这是我使用的是MSVC的方式
By the way I'm using MSVC
推荐答案
您需要创建一个C API的暴露你的C ++ code的功能。基本上,你需要写一个声明为externC,并有一个纯C API(不使用类,例如)封装了C ++库C ++ code。然后使用您已经创建了纯C包装库。
You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.
您C API可以任意跟随一个面向对象的风格,即使C不是面向对象的。例如:
Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:
// *.h file
// ...
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
typedef void* mylibrary_mytype_t;
EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);
#undef EXTERNC
// ...
// *.cpp file
mylibrary_mytype_t mylibrary_mytype_init() {
return new MyType;
}
void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
delete typed_ptr;
}
void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
MyType* typed_self = static_cast<MyType*>(untyped_self);
typed_self->doIt(param);
}
这篇关于如何调用从C C ++函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!