引数を変更する関数を使ってc拡張を記述したいと思います。それは可能ですか?引数を変更するPythonの拡張モジュールを書く
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"になります。
ありがとうございました。
'int'sと' float'sはPythonでは不変です。そうではありませんが、期間を変更することはできません。 – Kundor
私はオンラインで検索しました。 int/flow変数へのポインタを関数に渡すことは可能ですか?そうすれば、関数はポインタが指す値を取得して変更できますか?またはこれは(stackoverflow.com/questions/8056130/immutable-vs-mutable-types)でも動作しますか? – rxu
いいえ値は変更できません。 Pythonでは、値が3の単一のintオブジェクトがあります。結果が3の操作を行うと、このオブジェクトが返されます。何とかあなたがメモリ位置にアクセスし、その内容を例えば4に変更すると、1 + 2はどこでも4になります。これは悪いことです。 – Kundor