python - 编写一个修改参数的 python c 扩展

标签 python c python-c-extension

我想写一个带有修改其参数的函数的 c 扩展。这可能吗?

helloworld.c

#include <Python.h>
// adapted from http://www.tutorialspoint.com/python/python_further_extensions.htm


/***************\
* Argument Test *
\***************/
// Documentation string
static char arg_test_docs[] =
    "arg_test(integer i, double d, string s): i = i*i; d = i*d;\n";

// C Function
static PyObject * arg_test(PyObject *self, PyObject *args){
    int i;
    double d;
    char *s;
    if (!PyArg_ParseTuple(args, "ids", &i, &d, &s)){
        return NULL;
    }
    i = i * i;
    d = d * d;
    Py_RETURN_NONE;
}

// Method Mapping Table
static PyMethodDef arg_test_funcs[] = {
    {"func", (PyCFunction)arg_test,  METH_NOARGS , NULL },
    {"func", (PyCFunction)arg_test,  METH_VARARGS, NULL},
    {NULL, NULL, 0, NULL}
};

void inithelloworld(void)
{
    Py_InitModule3("helloworld", arg_test_funcs,
                   "Extension module example3!");
}

设置.py

from distutils.core import setup, Extension
setup(name='helloworld', version='1.0',  \
      ext_modules=[Extension('helloworld', ['helloworld.c'])])

安装:

python setup.py install

测试:

import helloworld
i = 2; d = 4.0; s='asdf'
print("before: %s, %s, %s" % (i,d,s))
helloworld.func(i,d,s)
print("after: %s, %s, %s" % (i,d,s))

测试结果:

before: 2, 4.0, asdf
after: 2, 4.0, asdf

整数和 double 值没有改变。 结果应该是“after: 4, 16.0, asdf”

感谢您的帮助。

最佳答案

I want to write a c extension with a function that modifies its argument. Is that possible?

仅在普通功能可能实现的范围内。如果传递给你的对象是可变的,你可以改变它们,但你不能重新分配用于传递给你这些对象的任何变量。 C API 不允许您解决这个问题。

您要编写的函数将无法运行。

关于python - 编写一个修改参数的 python c 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37823232/

相关文章:

Python 无法导入 (cython) 共享库

Python多文件写入问题

python - Shebang/选择脚本要运行的 Python 版本

c++ - 在C++中实现C-API文本 block 类时出错

python - 将 Python 长整数转换为 C 字符数组

python - ctypes.ArgumentError : Don't know how to convert parameter

python - Django RedirectView 和 reverse() 不能一起工作?

c - 有没有阻塞内存的系统调用

c - 在 c 中使用带有命令行参数的 if 语句

python - 如何在 Python C API 中实现多态性?