将C++接口封装成C函数

本文介绍了如何将C++的接口封装成C函数,通过创建C++的动态链接库(.so文件),并使用C语言调用该库中的函数实现跨语言交互。详细步骤包括编写C++类,生成C++动态库,编写C函数接口,以及在C程序中使用dlopen和dlsym函数动态加载并调用C++接口。

在某些情况下,需要将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 <iostream> 

#include "cy_test.h"

 

A::A(){}

A::~A(){}

int A::gt()

{

    s=10;

}

int A::pt()

{

 

    std::cout<<s<<std::endl;

}

 

编译:g++ -shared -o libmy.so cy_test_body.cpp 生成libmy.so文件。

将该so文件cp到/usr/lib下。

------------------------------------

然后,对该接口进行封装:

[chengyi@localhost cytest]$ cat test.cpp 

#include <iostream>

#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 <stdio.h>

#include <dlfcn.h>

 

#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 

10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值