call by reference (c module)

Alex Martelli aleax at aleax.it
Wed Nov 13 05:58:22 EST 2002


Brian Lee wrote:

> Hi, I am newbie!
> 
> (1) call by reference
> 
> I am trying to make a simple C module. Follow is a brief example
> for my situation. How can I use `call by reference' to put argument
> value to C module?
> 
> a = 1
> import some_c_module
> some_c_module.function(a) # function change variable a to 2
> print a                   # I want a to be 2 (not 1)

You cannot do this.  There is no way for a called function to
mess with the bindings of names-to-values in its caller (no
matter whether the called function is coded in C or Python).

The Pythonic approach is to have a called function RETURN its
results.  If the function has several values to return, the
function should return a tuple of results.


> (2) un-fixed size of arguments to a C module.
> 
> Is there any (easy) way to put un-fixed size of arguments to a
> C module? I tested PyArg_ParseTuple() but I don't know how to
> manage un-fixed size of values with it.

If you really have a fixed number of arguments, some of which are
optional, e.g:

    int a, b, c, d=23, e=42;
    if(!PyArg_ParseTuple(args, "iii|ii", &a, &b, &c, &d, &e))
        return NULL;

the | in the format string means all following arguments are
optional; be sure to give the default value to the corresponding
C-level variables before you call PyArg_ParseTuple, since those
variables won't be changed if the corresponding optional argument
is not present.

If you just want your C code to receive and handle a tuple with
any number of Python objects, one per argument that was passed,
you already have that -- it's the "args" tuple.  You can for
example learn how many arguments were passed with
PyTuple_Size(args), peek at e.g. the 3rd one with PyTuple_GetItem(args, 2), 
and so on.  In other words, you are absolutely NOT limited to using
PyArgs_ParseTuple to get at your arguments -- you can treat the
args tuple just as you might any other tuple of Python objects.


Alex






More information about the Python-list mailing list