博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python调用C/C++程序
阅读量:7105 次
发布时间:2019-06-28

本文共 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 #include 
2 #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/

你可能感兴趣的文章
自定义BeanUtils的populate方法实现
查看>>
部署Nginx+Tomcat负载均衡集群
查看>>
Unable to instantiate default tuplizer [org.hib...
查看>>
Django模板--反向解析
查看>>
linux搭建grafana
查看>>
tomcat环境变量
查看>>
linux服务器搭建 NAT和DHCP超详细
查看>>
Java并发编程40道面试题及答案——面试稳了
查看>>
“大数据”领域里的“不明觉厉”
查看>>
调试Python程序代码的几种方法总结
查看>>
我的友情链接
查看>>
大数据处理相关的好博文
查看>>
Java IO:BIO和NIO区别及各自应用场景
查看>>
Google 宣布将会关闭消费者版本 Google+
查看>>
Linux 平台下的漏洞扫描器 Vuls
查看>>
Mysql常用命令
查看>>
maven servlet上传文件
查看>>
Query对象和DOM对象使用说明
查看>>
Ubuntu11.10下安装VMwareTools步骤
查看>>
Windows 套接字详解、 值,和的含义
查看>>