[英]Using C++ code in a C program and Vice-Versa
我目前正在編寫一個非常低級的C程序與一個較高級的C ++程序之間的接口。 它們的關聯方式是通過鏈接列表進行的:C程序具有一個鏈接列表,並且該接口將存儲在該鏈接列表中每個節點中的信息轉換為C ++向量。 流程本身不是程序。 問題是如何從C程序調用該C ++函數。 讓我給你一些啟示:
int importData(List *head, char * source, char * dest);
在名為import_helper.cpp
的C ++文件中import_helper.cpp
。 我定義了聲明,並在上面顯示了,然后是實現,因此編譯不會抱怨。 在C程序import.c
,我試圖調用該函數:記住,List是import.c
定義的結構。現在,在import.c
我具有:
#if defined(_cplusplus)
extern 'C' {
#endif
typedef struct list{
struct list *next
.. other additional data goes here ...
}List;
int importData(List *head, char *source, char *dest);
#if defined(_cplusplus)
}
#endif
在import_helper.cpp
標頭中,我執行#include "import.c"
。 import.c
沒有.h文件(有人編寫了該代碼,我個人認為這本身就是一個錯誤)。
編譯時,我得到:
error: expected unqualified-id before 'class'
error: conflicts with the new declaration with 'C' linking
error: previous declaration of 'void getPassword(char *)' with 'C++' linkage
那只是一個例子。 但是,我相信import.c
是用gcc
編譯的,而我的Build
文件import_help.cpp
用g++
編譯的import_help.cpp
。 那可能是原因嗎? 我還有其他采用類似方法的文件,因此我對此不太確定。 任何想法? 謝謝
該解決方案是創建一個import_helper.h
文件,然后在import_helper.cpp
我有它包括( #include "import_helper.h"
兩個) import_helper.cpp
和import.c
。 在import_helper.h
我有:
extern "C"{
typedef struct list{
... /*some code goes here */
struct list* next;
}List;
int importData(List *, char*, char*);
}
因此, .c
和.cpp
共享相同的數據。
您可以通過編寫在后端使用C ++的DLL在兩個項目之間共享通用代碼。 只要為C進行了聲明,您就應該能夠從C或C ++程序中調用已定義的方法。
在.cpp文件中定義importData時,還需要將其放在extern“ C”(注意雙引號)塊中:
extern "C"{
int importData(List *head, char *source, char *dest){
blah blah blah
...
}
}
而且從錯誤void getPassword(char *)
需要它。
C ++可以引發異常。
確保C ++代碼中的“ C”接口能夠捕獲所有內容,並返回錯誤狀態,並且可能返回某種cstring之類的消息,因此您不會遇到任何意外的程序終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.