您的位置:首页 > 编程语言 > Python开发

extending python with c

2017-10-10 12:38 253 查看

c_fib.c

#include <Python.h>

int Cfib(int n)
{
if (n < 2) {
return n;
} else {
return Cfib(n-1) + Cfib(n-2);
}
}

static PyObject* fib(PyObject* self, PyObject* args)
{
int n;
if (!PyArg_ParseTuple(args, "i", &n)) {
return NULL;
}
return Py_BuildValue("i", Cfib(n));
}

static PyObject* version(PyObject* self)
{
return Py_BuildValue("s", "Version 1.0");
}

static PyMethodDef myMethods[] = {
{"fib", fib, METH_VARARGS, "Calculates the Fibonacci number."},
{"version", (PyCFunction)version, METH_NOARGS, "Returns the version."},
{NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initc_fib(void)
{
(void)Py_InitModule("c_fib", myMethods);
}

setup.py

from distutils.core import setup, Extension

module = Extension('myModule', sources = ['myModule.c'])

setup(name='PackageName',
version='1.0',
description='This is a package for myModule',
ext_modules=[module])

install mingw gcc.exe

python setup.py build

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: