Python带有C扩展的Hello World

示例

以下C源文件(我们将hello.c出于演示目的将其调用)生成名为的扩展模块hello,其中包含一个函数greet():

#include <Python.h>
#include <stdio.h>

#if PY_MAJOR_VERSION >= 3
#定义IS_PY3K
#endif

static PyObject *hello_greet(PyObject *self, PyObject *args)
{
    const char *input;
    if (!PyArg_ParseTuple(args, "s", &input)) {
        return NULL;
    }
    printf("%s", input);
    Py_RETURN_NONE;
}

static PyMethodDef HelloMethods[] = {
    { "greet", hello_greet, METH_VARARGS, "Greet the user" },
    { NULL, NULL, 0, NULL }
};

#ifdef IS_PY3K
static struct PyModuleDef hellomodule = {
    PyModuleDef_HEAD_INIT, "hello", NULL, -1, HelloMethods
};

PyMODINIT_FUNC PyInit_hello(void)
{
    return PyModule_Create(&hellomodule);
}
#else
PyMODINIT_FUNC inithello(void)
{
    (void) Py_InitModule("hello", HelloMethods);
}
#endif

要使用编译gcc器编译文件,请在您喜欢的终端上运行以下命令:

gcc /path/to/your/file/hello.c -o /path/to/your/file/hello

要执行greet()我们先前编写的功能,请在同一目录中创建一个文件,然后调用它hello.py

import hello          # 导入编译的库
hello.greet("Hello!") # runs the greet() function with "Hello!" as an argument