Python调用C/C++

版权声明:本文为博主原创文章,转载需添加原文链接。 https://blog.csdn.net/makenothing/article/details/84993226

Python调用C/C++

方法:

  1. python提供的API调用C
  2. boost工具进行封装
  3. Python 标准库自带的 ctypes 模块
  4. Swig工具

ctypes 模块

ctypes是Python标准库提供的调用动态链接库的模块,相对1)2)来说不需要对源代码进行破坏,只需要对相应的c++数据类型进行python的转换。
示例:

// file: sum.c
#include <stdio.h>
#include <stdlib.h>

int sum(int x){
    int i, result=0;
    for(i=0; i<=x; i++){
        result+=i;
        }
    if(x > 100)
        exit(-1);
    return result;
};

生成linux下的动态链接库

gcc sum.c -fPIC -shared -o sum.so
# file: test.py
import ctypes
so = ctypes.CDLL('./sum.so')
print(so.sum(5))

测试:

python test.py
output: 15

API调用C

主要方法是在c++文件中借助Python提供的头文件python.h,对C/Cpp函数进行封装。然后将它编译为一个动态链接库(一个Module)。最后在Python文件中将这个module 加载进去,就可以调用了。具体例子请见http://blog.csdn.net/marising/article/details/2845339

boost工具进行封装

相对1)来说更为方便,但是和1)一样都需要对原C代码进行破坏。具体例子请见http://blog.csdn.net/marising/article/details/2917827

Swig

Swig和boost一样是一个对C进行封装的工具,但是和boost不一样,它不需要对源代码进行破坏,只需要新增一个接口文件对需要封装的函数和类进行描述,swig会自动对c代码封装成一个能被调用的module供Python调用。

  1. 安装swig
  2. 编写c程序
    //hello.c
    #include<stdio.h>
    #include"hello.h"
    void sayhello(const char* name)
    {
    printf(“hello %s!\n”, name);
    }

编写hello.h头文件:
extern void sayhello(const char* name);
3. 编写c程序和python之间的接口文件hello.i

%module hello
%{
extern void sayhello(const char* name);
%}
extern void sayhello(const char* name);

以上是swig接口的固定格式,其中module命令指定该模块的模块名
4. 编译生成地址无关目标.o文件
(1)编译以上hello.i文件:$ swig -python hello.i
这一步通过hello.i的指导,通过swig编译生成hello_wrap.c文件
(2)编译hello.c和hello_wrap.c,生成目标文件hello.o hello_wrap.o
$ gcc -fpic -c hello.c hello_wrap.c -I/usr/include/python2.7
5. 把地址无关文件链接成共享库
把hello.o hello_wrap.o链接生成hello.so。注意:这里的目标文件为_hello.so,注意下划线,为什么需要加下划线?因为第4.1生成的hello_wrap.c中的目标共享库是_hello.so,如果这里指定的是hello.so,会导致import hello出错!!!

$ ld -shared hello.o hello_wrap.o -o _hello.so
6. 通过python import导入python上下文
1680085@bjmod001:~/swig_test/hello$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.

import hello
hello.sayhello(“test”)
hello test!

7.在python调用c程序

猜你喜欢

转载自blog.csdn.net/makenothing/article/details/84993226