C語言調用C++庫接口的方法概述

最近需要在由純c語言編寫的代碼中調用C++的動態庫,在網上找了一些資料,現在總結下解決方法。

主要的思想就是將C++的動態庫再封裝一層,在這一層編寫C語言的函數api,這API中使用C++動態庫提供的類;

具體例子如下:

1,假如C++動態庫包含如下代碼:
//myclass.h

#ifndef _MYCLASS_H
#define _MYCLASS_H
class MyClass
{
    public:
        void print();
};
#endif

//myclass.cc

#include <iostream>
#include "myclass.h"
using namespace std;
 
void
MyClass::print()
{
    cout << "MyClass::print() called" << endl;
}

編譯鏈接生成動態庫:libmyclass.so
g++ myclass.cc -shared -o libmyclass.so -I./ -fPIC

2,封裝libmyclass.so中類的接口,生成libmyfunc.so
//myfunc.h

#ifndef _MYFUNCTION_H
#define _MYFUNCTION_H
 
#ifdef _cplusplus
extern "C" {
#endif
    void myprint();
#ifdef _cplusplus
}
#endif
#endif

//myfunc.c

#include "myclass.h"
#ifndef _cplusplus
#define _cplusplus
#include "myfunc.h"
#endif
void
myprint()
{
    MyClass mc;
    mc.print();
}

編譯鏈接生成動態庫(C語言接口):
g++ myfunc.c -shared -o libmyfunc.so -L./ -lmyclass -fPIC -Xlinker -rpath=./
3,測試libmyfunc.so中提供的接口
//main.c

#include "myfunc.h"
int 
main(int argc, char **argv)
{
    myprint(); 
}

編譯鏈接生成可執行代碼:
gcc main.c -o main -lmyfunc -L./ -I. -Xlinker -rpath=./
執行main文件,輸出如下:
MyClass::print() called
ok,大功搞成!!
注意事項:
1,注意myfunc.so必須是用g++來生成的,如果使用gcc,會不識別其中的類(這個解釋不一定正確)
2,注意myfunc.h中_cpluscplus的用法,因爲myfunc.h被main.c和myfunc.c兩個文件用到,而extern僅被g++能夠識別,
而不能夠被gcc識別,解釋的不一定對,還沒有想清楚。。。。。
本文地址:http://www.yaronspace.cn/blog/index.php/archives/1046

來自yaronspace.cn  本文鏈接:http://yaronspace.cn/blog/archives/1046 
發佈了87 篇原創文章 · 獲贊 28 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章