c++庫 c語言接口


 

    //code in add.cxx 
    #include "add.h"
    int sample::method()
    {
        cout<<"method is called!\n";
    }

    //code in add.h 
    #include <iostream>
    using namespace std;
    class sample
    {
        public:
        int method();
    };

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

    //code in mylib.cxx
    #include "add.h"
    #ifndef _cplusplus
    #define _cplusplus
    #include "mylib.h"
    #endif
     
    int myfunc()
    {
        sample ss;
        ss.method();
        return 0;
    }

    //code in 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 <stdio.h> 
    #include <dlfcn.h>
    #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()函數也能執行,這里介紹的是常規調用庫函數的方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM