Modifying Python parms passed to C function?

Cedric Adjih adjih at crepuscule.com
Thu Aug 31 12:05:32 EDT 2000


www.nkn.net <tririch at connect.net> wrote:
> I've been creating some C extension functions, and up until now have used
> dictionaries to mimic C-style structs. Since dictionaries are returned as a
> borrowed reference from PyArgs_ParseTuple I've been able to modify the
> dictionary and return results back to Python.
>
> Now I'm running into a problem with 'basic' types, such as ints and floats.
> What I want to do is essentially mimic a functions like this:
>
> int    myFunc(int *parm1, float *parm2)
> {
>     *parm1 = ...
>     *parm2 = ...
>
>     return 1;
> }
>
> Looking over the Python C API, I can see no way of pulling this off.  If I
> extract the two params into a native int and float type with
> PyArgs_ParseTuple, then of course any mods I make to those variables are
> within my local stack frame, and do not affect the passed parameters.  I can
> instead ask PyArgs_ to parse out the PyIntObject and PyFloatObject params as
> Python objects, but I can see no way to assign a new value into these using
> the C API.  This seems like such a basic necessity that I'm sure I'm simply
> overlooking it in the documentation. Can anyone point me in the right
> direction?

  Well, unless I didn't understand your problem, there is no way
to do it in pure Python either:

def myFunc(parm1, parm2):
    parm1=...
    parm2=...
    ...
    return 1
    
Doesn't change parm1 and parm2 they are integer (immutable).

So I think this is the key of your problem.
Either you can pass some mutable object holding one arg for each
arg (for instance a list), or, much cleaner, you simply return 
the parm1,parm2 in a tuple (along with 1). In Python

def myFunc(parm1, parm2):
   ...
   return 1, parm1, parm2

-- Cedric



More information about the Python-list mailing list