views:

32

answers:

2

A value which is a PyUnicodeObject need to be passed to PyObject variable. Is there any conversion method for that?

thanks karnol

+2  A: 

PyUnicodeObject is a subset of PyObject so there shouldn't be any problem passing it.

Delan Azabani
...except of course that the C compiler cannot possibly KNOW that (having no concept of subset, subclass, inheritance, etc) so you DO need a cast (pointer to pointer cast) as I explain in my answer.
Alex Martelli
+2  A: 

You can just use a cast in your C code for this purpose:

PyUnicodeObject *p = ...whatever...;
callsomefun((PyObject*)p);

All the various specific, concrete types PyWhateverObject can be thought of as being "derived from" PyObject. Now C does have the concept of inheritance so there's no "derived" in it, but the Python VM synthesizes it very simply, by ensuring every such object's memory layout "starts with" a header that exactly corresponds to what a PyObject struct would be (there's a macro for that). This guarantees that normal C casting of pointers (although technically "risky" as the compiler cannot check that correctness -- if you cast the wrong thing you'll just crash during runtime;-) works as intended when used correctly between a pointer to PyObject and any pointer to a specific, concrete Python type struct.

Alex Martelli
tel me forPyUnicodeObject type -> PyBytesObject typePyUnicodeObject *p = ...whatever...;callafun((PyByteObject*)p);Got a Bus Error.
dizgam
@kamol, each of `PyUnicodeObject` and `PyBytesObject` is a _separate_ "conceptual subclass" of `PyObject`, so the cast would not work there (and that's **not** what you asked in your Q, so I suggest you edit it to cover your **real** question). For your very specific and completely different current question, see http://docs.python.org/py3k/c-api/unicode.html#PyUnicode_Encode (and be sure to use a local variable for the byte object you thus create as you'll have to decref it after the call is done, unless what you're calling is a rare function that _steals_ a reference).
Alex Martelli