上一篇《windows下搭建python的C模块的visual studio编译器》介绍了如何用vs2017搭建在windows环境下的python c模块编译器。接下来我们编一个简单的c模块来用这个系统来完成编译。
首先,建立一个目录,例如helloworld。
在该目录下面建立一个setup.py文件,内容如下:
#setup.py
from setuptools import setup, Extension
module1 = Extension('helloword',
sources = ['src/helloworld.c'])
setup (name='helloword',
version='1.0',
author='geastwind',
author_email='2524890082@qq.com',
license='MIT',
description = "The helloword API",
url='',
ext_modules=[module1])
该文件主要是定义模块名称以及包含哪些源文件。
这里模块名称是'helloworld',这里源文件只有一个:'src/helloworld.c'。如果有多个,在sources列表中添加即可。
在子目录src中建立一个helloworld.c,内容如下:
//helloworld.c
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <time.h>
PyObject*
helloword(PyObject* self, PyObject* Py_UNUSED(args)) {
printf("Hello world!\n");
return PyLong_FromLong(12345);
}
static PyMethodDef helloword_functions[] = {
{ "hello", (PyCFunction)helloword, METH_NOARGS, PyDoc_STR("now\n-\n\nHello world demo.") },
{ NULL, NULL, 0, NULL }
};
PyDoc_STRVAR(helloword_doc, "The helloword module");
static PyModuleDef helloword_def = {
PyModuleDef_HEAD_INIT,
"helloword",
helloword_doc,
-1, /* m_size */
helloword_functions, /* m_methods */
NULL, /* m_slots */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC PyInit_helloword() {
PyObject* m = PyModule_Create(&helloword_def);
if (!m)
{
return NULL;
}
PyModule_AddStringConstant(m, "__author__", "geastwind");
PyModule_AddStringConstant(m, "__version__", "1.0.0");
return m;
}
这个helloworld模块只定义了一个接口,外部的名字是helloworld.hello,内部实现的函数是helloword(PyObject* self, PyObject* Py_UNUSED(args));其功能是打印输出hello world!,并返回一个整数值12345(指定为long类型).
然后,在helloworld目录下运行:
python setup.py build install
完成模块的编译和安装。使用也很简单:
import helloword
ret=helloword.hello()
print(ret)
运行后显示
hello world!
12345
最后,我们可以编译复杂的模块,例如webrtcvad等。
安装webrtcvad的时候会自动下载webrtcvad-2.0.10.tar.gz(也可以直接到下面下载:https://files.pythonhosted.org/packages/89/34/e2de2d97f3288512b9ea56f92e7452f8207eb5a0096500badf9dfd48f5e6/webrtcvad-2.0.10.tar.gz)
下载后展开到webrtcvad-2.0.10目录,到该目录运行python setup.py build install即可编译并安装。