标签:rom nav port cto tde include mft pyc url
编程中会遇到调用其他语言到库,这里记录一下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 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 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 ##call 11 fun=lib.init ###类似C/C++函数指针 12 fun.restype = c_int ##设置函数返回值类型 13 print fun(8); 14 print "*" * 20 15 16 ##call 17 fun=lib.is_inited 18 fun.restype = c_bool 19 print fun(); 20 print "*" * 20 21 22 ##call 23 fun=lib.str2 24 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 "*" * 20 32 33 ##call 34 print lib.add(1, 2); 35 print "*" * 20
执行结果:
标签:rom nav port cto tde include mft pyc url
原文地址:http://www.cnblogs.com/xudong-bupt/p/7025728.html