Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if PyObject is nullptr

I am using a Python C Api to fill the list containing the PyObject* elements and transfer it to the function in Python. Everything went very smoothly but there is one issue - transfered list in Python is containing odd <NULL> entries. List is containing "wanted" objects as well so it looks like it's almost-working.

This is the list preview:

[<NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <dbg.TBack object at 0x19675870>, <interface.Grid object at 0x196758B0>, <interface.Grid object at 0x196758F0>, <interface.slp object at 0x196757D0>]

Code I am using for filling the list in Python C API.

PyObject* list = PyList_New(objectsList.size());
PyObject* handle;

for (auto child : objectsList) {
    if (!child) {
        continue;
    }

    handle = child->GetHandle(); // handle = PyObject*
    if (!handle) {
        continue;
    }

    PyList_Append(list, handle);
}

return list; // push

I have tried adding if(!handle) checks but it doesn't seem to have any result in practise.

Question: How can I get rid of the <NULL> entries in my list?

like image 314
Lucas Avatar asked Sep 01 '26 11:09

Lucas


1 Answers

Try this solution

if (handle == Py_None) {
    continue;
}   

Or

int PyObject_Not(PyObject *o)

Returns 0 if the object o is considered to be true, and 1 otherwise. This is equivalent to the Python expression not o. On failure, return -1.

Otherwise, maybe you could check handle's string representation. According to the documentation, you might be able to use some combination of

int       PyObject_Compare(PyObject *o1, PyObject *o2)
PyObject* PyObject_Repr   (PyObject *o)

I'm thinking something like

PyObject* null_str   = Py_BuildValue("null_str", "<NULL>");
PyObject* handle_str = PyObject_Repr(handle);
if (!PyObject_Compare(null_str, handle_str)) {
    continue;
}
like image 179
maddouri Avatar answered Sep 03 '26 00:09

maddouri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!