將C 介面封裝成C函式

2021-05-01 22:34:12 字數 1437 閱讀 9201

在某些情況下,需要將c++的介面封裝成c函式。

首先,我們準備乙個c++的so檔案,它由以下h和cpp檔案生成:

[chengyi@localhost cytest]$ cat cy_test.h 

class a

public:

a();

virtual ~a();

int gt();

int pt();

private:

int s;

[chengyi@localhost cytest]$ cat cy_test_body.cpp 

#include

#include "cy_test.h"

a::a(){}

a::~a(){}

int a::gt()

s=10;

int a::pt()

std::cout<

編譯:g++ -shared -o libmy.so cy_test_body.cpp 生成libmy.so檔案。

將該so檔案cp到/usr/lib下。

然後,對該介面進行封裝:

[chengyi@localhost cytest]$ cat test.cpp 

#include

#include "cy_test.h"

extern "c"

int f();

int f()

a a;

a.gt();

a.pt();

return 0;

編譯: gcc -shared -o sec.so test.cpp -lmy  生成sec.so檔案,也cp到/usr/lib下。

[chengyi@localhost cytest]$ cat test.c

#include

#include

#define sofile "sec.so"

int (*f)();

int main()

void *dp;

char * error;

dp=dlopen(sofile,rtld_lazy);

if (!dp) {

fprintf (stderr, "%s/n", dlerror());

return 1;

f=dlsym(dp,"f");

if ((error = dlerror()) != null)  {

fprintf (stderr, "%s/n", error);

return 1;

f();

return 0;

編譯: gcc -o test test.c -rdynamic -ldl  

這裡,由於用到了dlopen等動態載入函式,所以需要-rdynamic -ldl引數。

執行:[chengyi@localhost cytest]$ ./test 

open nsfw封裝成介面

承接上文 黃圖識別 open nsfw 為了使用的方便和提供別人好用,想把open nsfw封裝成http形式的介面,別人通過上傳,就可以得到這的nsfw score.由於本人技術有限,python不太熟悉,自己整理了一套方案如下 1因為需要上傳到伺服器之後,才能呼叫python的 nsfw,所以這...

函式封裝成DLL

新建專案 visual c win32 win32專案 名稱為mydll 選擇儲存目錄 確定下一步 應用程式型別 dll,附加選項 空專案 完成。新增原始檔mydll.cpp extern c declspec dllexport int add int a,int b declspec dllex...

C 和C混合程式設計 C語言函式封裝成dll

這次大作業小組利用c語言寫 最後使用winform設計gui,自然要在c 中呼叫c,該篇記錄如何把c封裝為dll。大作業模擬溫度感測器,c語言 為兩部分,一部分為sensor服務端serve,可以生成隨機溫度來模擬溫度感測器,另一部分為workstation客戶端client,可以使用其傳送指令st...