python c扩展模块的方法

注意点和要点:

1、python2.x和python3.x的函数形式不一样,一定要注意。

比如:Py_InitModule函数是在python2.x中使用的,而python3.x没有这个函数。

2、python setup.py build //生成模块

3、python setup.py install //生成模块并安装模块

举例说明:

1、其中 hello.c文件

#include <Python.h>

static PyObject* helloworld(PyObject* self) {

return Py_BuildValue("s", "Hello, helloworld Python");

}

 

static char helloworld_docs[] =

"helloworld( ): Any message you want to put here!!\n";

 

static PyMethodDef helloworld_methods[] = {

{"helloworld", (PyCFunction)helloworld,

METH_NOARGS, helloworld_docs},

{NULL}

};

 

static struct PyModuleDef helloworld_def =

{

PyModuleDef_HEAD_INIT,

"helloworld", /* name of module */

"", /* module documentation, may be NULL */

-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */

helloworld_methods

};

 

PyMODINIT_FUNC PyInit_helloworld(void)

{

return PyModule_Create(&helloworld_def);

}

 

2、setup.py 文件

 

from distutils.core import setup, Extension

setup(name='helloworld', version='1.0', \

ext_modules=[Extension('helloworld', ['hello.c'])])

 

安装完成后检测是否正确的方法:

 

test.py文件

 

import helloworld

 

#print("helloworld\r\n")

 

print(helloworld.helloworld())

 

说明:

hello.c setup.py test.py 在Ubuntu 18.04.3 LTS和win10下的pycharm都可以实现。已经成功在两个环境下调用model helloword

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值