問題描述
這個我知道.
從 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++ 代碼的功能.基本上,您將需要編寫聲明為 extern "C" 并且具有包裝 C++ 庫的純 C API(例如不使用類)的 C++ 代碼.然后使用您創建的純 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++ 函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!