东方耀AI技术分享
标题:
python调用c/c++编译出的so库(没有使用swig)
[打印本页]
作者:
东方耀
时间:
2021-12-6 14:10
标题:
python调用c/c++编译出的so库(没有使用swig)
python调用c/c++编译出的so库(没有使用swig)
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <stdio.h>
// 将cpp编译成so
// g++ -shared -Wl,-soname,test -o test.so -fPIC test.cpp
class Test{
private:
double _calculate(int a, double b);
public:
double calculate(int a, double b, char c[], int * d, double * e, char ** f);
};
double Test::_calculate(int a, double b){
double res = a+b;
std::cout<<"res: "<<res<<std::endl;
return res;
}
double Test::calculate(int a, double b, char c[], int * d, double * e, char ** f){
std::cout<<"a: "<<a<<std::endl;
std::cout<<"b: "<<b<<std::endl;
std::cout<<"c: "<<c<<std::endl;
std::cout<<"d: "<<d[0] << ","<<d[1]<<std::endl;
std::cout<<"e: "<<e[0] << ","<<e[1]<<std::endl;
std::cout<<"f: "<<f[0] << ","<<f[1]<<std::endl;
return this->_calculate(a, b);
}
// 封装C接口 这样lib才能访问得到 这是暴露接口给python使用
extern "C"{
// 创建对象
Test* test_new(){
// 谁调这个 函数test_new()?
return new Test;
}
double my_calculate(Test* t, int a, double b, char c[], int * d, double * e, char ** f){
return t->calculate(a, b,c,d,e,f);
}
}
复制代码
# -*- coding: utf-8 -*-
__author__ = u'东方耀 微信:dfy_88888'
__date__ = '2021/12/6 下午1:36'
__product__ = 'PyCharm'
__filename__ = 'test'
import ctypes
# python调用c/c++编译出的so库(没有使用swig)
# 指定动态链接库
lib = ctypes.cdll.LoadLibrary('./test.so')
# 需要指定返回值的类型,默认是int
lib.my_calculate.restype = ctypes.c_double
class Test(object):
def __init__(self):
# 动态链接对象
self.obj = lib.test_new()
def calculate(self, a, b, c, d, e, f):
res = lib.my_calculate(self.obj, a, b, c, d, e, f)
return res
# 将python类型转换成c类型,支持int, float,string的变量和数组的转换
def convert_type(input):
# python调用c++ py的类型需要转换为c++可以识别的类型啊
ctypes_map = {int: ctypes.c_int,
float: ctypes.c_double,
str: ctypes.c_char_p
}
input_type = type(input)
if input_type is list:
length = len(input)
if length == 0:
print("convert type failed...input is " + input)
return None
else:
arr = (ctypes_map[type(input[0])] * length)()
for i in range(length):
arr[i] = bytes(input[i], encoding="utf-8") if (type(input[0]) is str) else input[i]
return arr
else:
if input_type in ctypes_map:
return ctypes_map[input_type](bytes(input, encoding="utf-8") if type(input) is str else input)
else:
print("convert type failed...input is " + input)
return None
if __name__ == '__main__':
t = Test()
A1 = 123
A2 = 0.789
A3 = "C789"
A4 = [456, 789]
A5 = [0.123, 0.456]
A6 = ["A123", "B456"]
print(t.calculate(convert_type(A1), convert_type(A2), convert_type(A3), convert_type(A4), convert_type(A5),
convert_type(A6)))
复制代码
欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/)
Powered by Discuz! X3.4