【发布时间】: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