I am debugging Python source code (CPython 3.4). I'm receiving a PyObject*. I would like to printf it.
For example (from Objects/floatobject.c of Python 3.4 source code):
PyObject *o_ndigits = NULL;
Py_ssize_t ndigits;
x = PyFloat_AsDouble(v);
if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
return NULL;
How do I printf o_ndigits? It is almost same as this question: Python: get string representation of PyObject?, but for Python3. With original solution, I got "undefined reference to PyString_AsString" error.
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.
Strings are Arrays Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.
PyObject is an object structure that you use to define object types for Python. All Python objects share a small number of fields that are defined using the PyObject structure. All other object types are extensions of this type. PyObject tells the Python interpreter to treat a pointer to an object as an object.
Both PyObject_Repr and PyObject_ASCII return a unicode str representation of the object. If your terminal doesn't use UTF-8, you probably want the ASCII escaped representation. Get the multibyte string with PyUnicode_AsUTF8 or PyUnicode_AsUTF8AndSize. The new implementation in 3.3 caches the UTF-8 byte string, so don't deallocate it after printing.
As to PyString_AsString, that became PyBytes_AsString or PyBytes_AS_STRING for the 3.x bytes type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With