2016-06-14 9 views
1

引数を変更する関数を使って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"になります。

ありがとうございました。

+2

'int'sと' float'sはPythonでは不変です。そうではありませんが、期間を変更することはできません。 – Kundor

+0

私はオンラインで検索しました。 int/flow変数へのポインタを関数に渡すことは可能ですか?そうすれば、関数はポインタが指す値を取得して変更できますか?またはこれは(stackoverflow.com/questions/8056130/immutable-vs-mutable-types)でも動作しますか? – rxu

+0

いいえ値は変更できません。 Pythonでは、値が3の単一のintオブジェクトがあります。結果が3の操作を行うと、このオブジェクトが返されます。何とかあなたがメモリ位置にアクセスし、その内容を例えば4に変更すると、1 + 2はどこでも4になります。これは悪いことです。 – Kundor

答えて

2

引数を変更する関数を使用してc拡張子を書きたいとします。それは可能ですか?

通常の機能では可能な程度に限ります。あなたに渡されたオブジェクトを変更可能なものに変更することはできますが、それらのオブジェクトを渡すために使用された変数を再割り当てすることはできません。 C APIはこれを回避することはできません。

書きたい機能が動作しません。

+0

ありがとうございます。関数に渡されたオブジェクトを変更するc拡張を書く方法は?同様に、intオブジェクトを取得し、オブジェクトを変更しますか? – rxu

+0

@rxu:Python intsは変更可能ではありません。 – user2357112

関連する問題