python实现c++中so库调用及dbus服务开发

本期介绍主要分两块,一块是python如何调用so库,另一块是dbus服务的注册与调用;

python调用so库

1. c++源码

# test.h文件

#include<iostream>
using namespace std;

extern "C"{
int cacl(int a, int b);
struct student{
        char sname[50];
        int score;
    };
student printInfo(student stu[], void callback(int));
}


# test.cpp文件

#include "test.h"  

extern "C"{
    int cacl(int a, int b){
        cout << "这是库文件内容" << endl;
        return a>b?a:b;
    }
    //创建学生结构体
    struct student;
    student printInfo(student stu[], void callback(int)){
        int total_score = 0;
        for(int i = 0; i < 3; i ++){
            cout << "第" << i+1 << "个学生名字是: " << stu[i].sname << endl;
            total_score += stu[i].score;
        }
        callback(total_score);
        return stu[0];
    }
}

# main.cpp文件

#include "test.h"

void func(int score){
    cout << "这是回调函数内容" << endl;
    cout << "获取分数总值" << score << endl;
}

int main(){
    int a = cacl(89, 5);
    cout << "这是main函数内容" << "  最大值是" << a << endl;
    student stu[3]={
        {"jack", 100},
        {"rose", 67},
        {"lili", 90}
    };
    student stt = printInfo(stu, func);
    cout << stt.sname << endl;
}

#  cd "/xxxx/" && g++ main.cpp test.cpp  -o main && "/xxx/"main 命令运行结果
这是库文件内容
这是main函数内容  最大值是89
第1个学生名字是: jack
第2个学生名字是: rose
第3个学生名字是: lili
这是回调函数内容
获取分数总值257
jack

main.cpp是为了测试test.cpp是否正常,可以不用管;

以上代码有几个需要注意的点:

  • extern "C", 这个在头文件和cpp文件中都得加上,不然在python中调用时总是报错找不到方法;
  • sname必须用char去定义,而不是string,否则python代码运行后会出现乱码;
  • printInfo方法的返回值,以上写法只能返回第一个元素,这一点懂C++的都明白,我不太会写C++,代码能调通就是我的极限了......

总之,以

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值