Linux C調用C++庫

來源:互聯網
上載者:User
linux010
linux資料庫網
Winterh
2007-11-29 0:45:50


章摘要: C調用C++函數庫,一般不能直接調用,需要將C++庫轉換成C介面輸出,方可以使用C調用,看下面的例子: aa.cxx
#include add.h int sample::method() { cout } aa.h #include using
namespace std; class sample { public: int method(); };
將上面的兩個檔案產生動態庫libaa.so放到 /usr/lib目錄下,編譯命令如下 sudo g++ -fpic -shared -g

C調用C++函數庫,一般不能直接調用,需要將C++庫轉換成C介面輸出,方可以使用C調用,看下面的例子:

aa.cxx

#include "add.h"

int sample::method()

{

cout<<"method is called!/n";

}

aa.h

#include <iostream>

#include <string>

using namespace std;

class sample

{

public:

int method();

};

將上面的兩個檔案產生動態庫libaa.so放到 /usr/lib目錄下,編譯命令如下

sudo g++ -fpic -shared -g -o /usr/lib/libaa.so aa.cxx -I ./

由於在C中不能識別類,所以要將上面類的成員函數封裝成C介面函數輸出,下面進行封裝,將輸出介面轉換成C介面。

mylib.cxx

#include "add.h"

#ifndef _cplusplus

#define _cplusplus

#include "mylib.h"

#endif

int myfunc()

{

sample ss;

ss.method();

return 0;

}

mylib.h

#ifdef _cplusplus

extern "C"

{

#endif

int myfunc();

#ifdef _cplusplus

}

#endif

在linux下,gcc編譯器並沒用變數_cplusplus來區分是C代碼還是C++代碼,如果使用gcc編譯器,這裡我們可以自己定義一個變數
_cplusplus用於區分C和C++代碼,所以在mylib.cxx中定義了一個變數_cplusplus用於識別是否需要“extern
"C"”將函數介面封裝成C介面。但是如果使用g++編譯器則不需要專門定義_cplusplus,編譯命令如下:

g++ -fpic -shared -g -o mylib.so mylib.cxx -la -I ./

main.c

#include

#include

#include "mylib.h"

int

main()

{

int (*dlfunc)();

void *handle; //定義一個控制代碼

handle = dlopen("./mylib.so", RTLD_LAZY);//獲得庫控制代碼

dlfunc = dlsym(handle, "myfunc"); //獲得函數入口

(*dlfunc)();

dlclose(handle);

return 0;

}

編譯命令如下:

gcc -o main main.c ./mylib.so -ldl

下面就可以執行了。

需要說明的是,由於main.c 和 mylib.cxx都需要包含mylib.h,並且要將函數myfunc封裝成C介面函數輸出需要“extern
"C"”,而C又不識別“extern "C"”,所以需要定義_cplusplus來區別處理mylib.h中的函數myfunc。

在main.c的main函數中直接調用myfunc()函數也能執行,這裡介紹的是常規調用庫函數的方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.