风火编程--python调用c++示例

python调用c++

c++文件中声明以c的方式编译

extern "C"{
    Test* 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);
   }
}

其中:
test_new()中创建了一个c++的Test类的实例,并返回
my_calculate()中传入Test的一个实例t, 并调用t的caculate()方法

c++文件编译成python调用的.so动态库

g++ -std=c++17 -shared  -fPIC -o  face.so test_jpeg_facedetect.cpp -lopencv_core 

其中:
test_jpeg_facedetect是临时的.o文件名
face.so 是编译成的的库文件名
test_jpeg_facedetect.cpp 是要编译的文件

编写python脚本

import ctypes
lib = ctypes.cdll.LoadLibrary('./test.so')
#需要指定返回值的类型,默认是int
lib.my_calculate.restype = ctypes.c_double

def convert_type(input):
    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
        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

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)))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值