Python调用C程序

来源:互联网 发布:js.users.51.la是什么 编辑:程序博客网 时间:2024/05/22 06:16

Python调用C程序

介绍两种方法,一种是在C文件中加上python.h头文件,较复杂,另一种是使用python中的ctypes包,较简单。


1. 在C文件中加上python.h头文件

c文件中写法要求较复杂
wrapper.c

#include <Python/Python.h>int fact(int n){  if (n <= 1)    return 1;  else    return n * fact(n - 1);}PyObject* wrap_fact(PyObject* self, PyObject* args){  int n, result;  if (! PyArg_ParseTuple(args, "i:fact", &n))    return NULL;  result = fact(n);  return Py_BuildValue("i", result);}static PyMethodDef exampleMethods[] ={  {"fact", wrap_fact, METH_VARARGS, "Caculate N!"},  {NULL, NULL}};'void initexample(){  PyObject* m;  m = Py_InitModule("example", exampleMethods);}

从终端进入.c文件所在文件夹
输入
gcc -shared -o example.so wrapper.c -framework Python
python程序中调用实例
import example
print example.fact(5)

2. 调用ctypes库

c文件不需要特殊格式
algo.c

#include<stdio.h>int sum(int a, int b){    return a+b;}int multiply(int a,int b){    return a*b;}

从终端进入.c文件所在文件夹
输入
gcc -shared -o algo.so algo.c -framework Python
python程序中调用实例
Main.py

import ctypesso=ctypes.CDLL("./algo.so")print so.sum(3,5)print so.multiply(3,5)

*注:本例在OSX上运行有效

0 0
原创粉丝点击