python - 使用 C 扩展扩展 python

标签 python c python-c-api python-c-extension

我正在尝试学习如何使用 C 扩展来扩展 python,到目前为止,我已经能够浏览官方的 python 文档来实现相同的目的。

浏览,我发现this有用的资源,解释了如何使用 C 扩展来扩展 python。因此,该示例如下所示:

#include <Python.h>

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

static PyObject*
fib(PyObject* self, PyObject* args)
{
    int n;

    if (!PyArg_ParseTuple(args, "i", &n))
        return NULL;

    return Py_BuildValue("i", _fib(n));
}

static PyMethodDef FibMethods[] = {
    {"fib", fib, METH_VARARGS, "Calculate the Fibonacci numbers."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initfib(void)
{
    (void) Py_InitModule("fib", FibMethods);
}

但是,我无法理解这段代码的作用:

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

特别是函数名称的 _ 部分。

如果有人能解释上面这段代码的作用,我将非常感激。

最佳答案

这只是简单的 C 代码。 _fib 函数计算第 n 个 fibonacci number .

名称开头的_没有任何特殊含义。它通常(至少在Python社区)用来表示“私有(private)”函数。他们可能使用 _fib 作为 C 函数,因为他们想使用 fib 作为包装器。

我相信该示例旨在展示如何以纯 C 形式实现核心功能,并添加可从 python 访问的包装器。

关于python - 使用 C 扩展扩展 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22410534/

相关文章:

python - 如何批量安装多个 Python 包?

Python:有没有办法绘制 ax + by + c = 0 形式的标准直线方程

c++ - 有什么方法可以通过在 C++ 中读取文件来构造函数指针

python - 看起来 Python C-API 中的 C 代码将 ptr 返回到堆栈变量。我错过了什么?

Python:对象身份问题?

python - 使用 Python 搜索 Lua 文件中的所有函数调用

将字符从字符串复制到C中的另一个字符串

c - 战舰: place ships

python - 'PyThreadState_SetAsyncExc' 导致 'SystemError: exception Exception() not a BaseException subclass'

python - 如何在 Python setup.py 脚本中将标志传递给 gcc?