本文共 2026 字,大约阅读时间需要 6 分钟。
编程中会遇到调用其他语言到库,这里记录一下Python调用C++。
Python底层是C, 所以调用C还是比较方便。调用C++有些麻烦。
Python提供了ctypes, 方便将Python类型转为C类型,实现传参数、函数返回类型的对应。ctypes网址:https://docs.python.org/2/library/ctypes.html
使用Python调用C/C++主要有三步:
(1) 编写好C/C++函数
(2) 把C/C++函数打包成库文件
(3) Python加载库文件并调用
代码记录一下:
1. pycall.h
1 #include2 #include 3 #include 4 5 class PythonTest{ 6 public: 7 PythonTest():_is_inited(false), _num(0){ 8 9 } 10 11 int init(int num){12 _num = num;13 _is_inited = true;14 printf("inited ok\n");15 return 0;16 } 17 18 int str2(char *src, char* dest, int len){19 if (src == NULL || len <= 0){ 20 return 0;21 } 22 23 int src_len = strlen(src);24 int num = snprintf(dest, len, "%s%s", src, src);25 return (num < len -1)? num:0;26 } 27 28 bool is_inited(){29 printf("_num = %d\n", _num);30 return _is_inited;31 } 32 33 private:34 bool _is_inited;35 int _num;36 };
2. pycall_so.cpp
1 #include "pycall.h" 2 3 extern "C" { 4 5 PythonTest py; 6 7 int init(int num){ 8 return py.init(num); 9 }10 11 bool is_inited(){12 return py.is_inited();13 }14 15 int str2(char* src, char* dest, int len){16 return py.str2(src, dest, len);17 }18 19 int add(int a, int b){ 20 return a + b;21 }22 23 }
3. pycall.py
1 #coding=utf-8 2 3 import ctypes 4 from ctypes import * 5 6 ##加载库文件 7 ll = ctypes.cdll.LoadLibrary 8 lib = ll("./libpycall.so") 9 10 ##call11 fun=lib.init ###类似C/C++函数指针12 fun.restype = c_int ##设置函数返回值类型13 print fun(8);14 print "*" * 2015 16 ##call17 fun=lib.is_inited18 fun.restype = c_bool19 print fun();20 print "*" * 2021 22 ##call23 fun=lib.str224 src = "hello world "25 dest = "*" * 30 ###申请buf, 用于保存返回结果 26 num = fun(src, dest, len(dest)) ###传递指针作为参数27 if num != 0:28 print dest[:num]29 else:30 print "buf is not ok"31 print "*" * 2032 33 ##call34 print lib.add(1, 2); 35 print "*" * 20
执行结果:
转载地址:http://cvjhl.baihongyu.com/