【问题标题】:Writing a python c extension that modifies argument编写一个修改参数的python c扩展
【发布时间】:2016-06-14 22:35:11
【问题描述】:

我想编写一个带有修改其参数的函数的 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

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

整数和双精度值不变。 结果应该是“after: 4, 16.0, asdf”

感谢您的帮助。

【问题讨论】:

  • ints 和 floats 在 Python 中是不可变的。所以不,它们不能被修改,期间。
  • 我在网上搜索了一下,发现确实如此。是否可以将指向 int/flow 变量的指针传递给函数?这样,函数是否可以获取和修改指针指向的值?或者这个(stackoverflow.com/questions/8056130/immutable-vs-mutable-types)可以工作吗?
  • 没有。该值无法更改。在 Python 中,有一个值为 3 的 int 对象。如果您执行任何导致 3 的操作,则返回此对象。如果您确实设法访问了内存位置并将其内容更改为 4,那么 1+2 在任何地方都是 4。这会很糟糕。

标签: python c python-c-extension


【解决方案1】:

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

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

你要写的函数不行。

【讨论】:

  • 感谢您的指点。如何编写一个 C 扩展来改变传递给函数的对象?比如,获取一个 int 对象,然后改变该对象?
  • @rxu:Python 整数是不可变的。
猜你喜欢
  • 2020-04-20
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 2012-12-10
  • 1970-01-01
相关资源
最近更新 更多