IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    C语言调用C++库接口的方法概述

    admin发表于 2010-12-28 09:30:12
    love 0

    最近需要在由纯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 
    #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

    您可能对下面文章也感兴趣:

    • linux gcc 下使用总结【继续更新】
    • linux下动态库的搜索路径顺序及常用命令


沪ICP备19023445号-2号
友情链接