Help in unwrapping a PyObject* returned by an embedded Python function

David Boddie davidb at mcs.st-and.ac.uk
Tue Jan 13 17:35:13 EST 2004


Read Roberts <rroberts at adobe.com> wrote in message news:<mailman.302.1073927909.12720.python-list at python.org>...

[Returning a string/tuple to a C function]

> In fact, I did try all combinations of
> 
> in the  Python call-back function :
> 	return myString
> 	return (myString)
> 
> and, in the  C calling function,
> 
> 	PyArg_ParseTuple(pyStringResult, "s", myString)
> 	PyArg_ParseTuple(pyStringResult, "(s)", myString)

I'm guessing here but, if you want to pass tuples around, have you tried
using the second form of each of the above with the following correction
to the Python code?

    return (myString,)

> Also, the Python documentation (and other working code examples I 
> have)  indicate that 'PyArg_ParseTuple',  unlike BuildValues, always 
> assumes the arguments are supplied in a argument tuple, even if there 
> is only one argumen.

Maybe. I haven't really thought about it.

> I speculate that an argument list object, as required by 
> PyArg_ParseTuple, is not in fact  a simple tuple., and that 
> PyArg_ParseTuple cannot be used to parse a regular tuple. Any idea if 
> this is correct?

I think that there's been a misunderstanding. Since your original message,
and some unavailable reply were quoted below your last message, I think I
can see where it happened.

> >In comp.lang.python, you wrote:
> >
> >>  Why does PyArg_ParseTuple fail to parse a  return value which is a
> >>  tuple?
> >>
> >>  However, the following does not work:
> >>  from Python callback function:		return (myString)
> >>  in calling C function:
> >>  	if (!PyArg_ParseTuple(pyStringResult, "s", name)) {
> >>    		dbprintf(4, "c: failed to parse return value\n");
> >>  		PyErr_Clear();
> >>  	}
> >>  PyArg_ParseTuple fails, and returns NULL. How come? By the
> >>  documentation, I would think that PyArg_ParseTuple would parse any
> >>  Python tuple object.

I don't know whether it does or not, but you have returned a string!
This happened because you need to use a trailing comma within the
brackets. This tells the interpreter that the return value is not
simply a string enclosed in brackets. You can see this from the
following output from an interactive session in Python:

>>> "string"
'string'
>>> ("string")
'string'
>>> ("string",)
('string',)

In your original example, you returned a string and converted it
successfully to a char pointer. Presumably, you wanted a more
general solution in order to catch any non-string objects returned
and turned to PyArg_ParseTuple. Maybe you could put the returned
object in a tuple and call PyArg_ParseTuple on the result, but
there's surely an easier way to check the validity of the return
value.

Hope this helps,

David



More information about the Python-list mailing list