本期介绍主要分两块,一块是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++,代码能调通就是我的极限了......
总之,以