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

时间:2021-06-02 23:17:07

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

我想用一个修改其参数的函数编写一个c扩展名。那可能吗?

helloworld.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!");
}

setup.py

setup.py

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

Installation:

安装:

python setup.py install

Test:

测试:

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))

Test Result:

测试结果:

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

The integer and double values are not changed. The result should be "after: 4, 16.0, asdf"

整数和双精度值不会更改。结果应该是“之后:4,16.0,asdf”

Thanks for the help.

谢谢您的帮助。

1 个解决方案

#1


2  

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

我想用一个修改其参数的函数编写一个c扩展名。那可能吗?

Only to the extent that it's possible with an ordinary function. You can mutate the objects passed to you, if they're mutable, but you can't reassign any variables used to pass you those objects. The C API doesn't let you get around this.

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

The function you want to write won't work.

您要编写的功能不起作用。

#1


2  

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

我想用一个修改其参数的函数编写一个c扩展名。那可能吗?

Only to the extent that it's possible with an ordinary function. You can mutate the objects passed to you, if they're mutable, but you can't reassign any variables used to pass you those objects. The C API doesn't let you get around this.

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

The function you want to write won't work.

您要编写的功能不起作用。