Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8893497
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T23:15:45+00:00 2026-06-14T23:15:45+00:00

I’m using python’s C API (2.7) in C++ to convert a python tree structure

  • 0

I’m using python’s C API (2.7) in C++ to convert a python tree structure into a C++ tree. The code goes as follows:

  • the python tree is implemented recursively as a class with a list of children. the leaf nodes are just primitive integers (not class instances)

  • I load a module and invoke a python method from C++, using code from here, which returns an instance of the tree, python_tree, as a PyObject in C++.

  • recursively traverse the obtained PyObject. To obtain the list of children, I do this:

    PyObject* attr = PyString_FromString("children");
    PyObject* list = PyObject_GetAttr(python_tree,attr);
    for (int i=0; i<PyList_Size(list); i++) {
        PyObject* child = PyList_GetItem(list,i); 
        ...
    

Pretty straightforward, and it works, until I eventually hit a segmentation fault, at the call to PyObject_GetAttr (Objects/object.c:1193, but I can’t see the API code). It seems to happen on the visit to the last leaf node of the tree.

I’m having a hard time determining the problem. Are there any special considerations for doing recursion with the C API? I’m not sure if I need to be using Py_INCREF/Py_DECREF, or using these functions or something. I don’t fully understand how the API works to be honest. Any help is much appreciated!

EDIT: Some minimal code:

void VisitTree(PyObject* py_tree) throw (Python_exception)
{
    PyObject* attr = PyString_FromString("children");
    if (PyObject_HasAttr(py_tree, attr)) // segfault on last visit
    {
        PyObject* list = PyObject_GetAttr(py_tree,attr);
        if (list)
        {
            int size = PyList_Size(list);
            for (int i=0; i<size; i++)
            {
                PyObject* py_child = PyList_GetItem(list,i);
                PyObject *cls = PyString_FromString("ExpressionTree");
                // check if child is class instance or number (terminal)
                if (PyInt_Check(py_child) || PyLong_Check(py_child) || PyString_Check(py_child)) 
                    ;// terminal - do nothing for now
                else if (PyObject_IsInstance(py_child, cls))
                    VisitTree(py_child);
                else
                    throw Python_exception("unrecognized object from python");
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T23:15:47+00:00Added an answer on June 14, 2026 at 11:15 pm

    One can identify several problems with your Python/C code:

    • PyObject_IsInstance takes a class, not a string, as its second argument.

    • There is no code dedicated to reference counting. New references, such as those returned by PyObject_GetAttr are never released, and borrowed references obtained with PyList_GetItem are never acquired before use. Mixing C++ exceptions with otherwise pure Python/C aggravates the issue, making it even harder to implement correct reference counting.

    • Important error checks are missing. PyString_FromString can fail when there is insufficient memory; PyList_GetItem can fail if the list shrinks in the meantime; PyObject_GetAttr can fail in some circumstances even after PyObject_HasAttr succeeds.

    Here is a rewritten (but untested) version of the code, featuring the following changes:

    • The utility function GetExpressionTreeClass obtains the ExpressionTree class from the module that defines it. (Fill in the correct module name for my_module.)

    • Guard is a RAII-style guard class that releases the Python object when leaving the scope. This small and simple class makes reference counting exception-safe, and its constructor handles NULL objects itself. boost::python defines layers of functionality in this style, and I recommend to take a look at it.

    • All Python_exception throws are now accompanied by setting the Python exception info. The catcher of Python_exception can therefore use PyErr_PrintExc or PyErr_Fetch to print the exception or otherwise find out what went wrong.

    The code:

    class Guard {
      PyObject *obj;
    public:
      Guard(PyObject *obj_): obj(obj_) {
        if (!obj)
          throw Python_exception("NULL object");
      }
      ~Guard() {
        Py_DECREF(obj);
      }
    };
    
    PyObject *GetExpressionTreeClass()
    {
      PyObject *module = PyImport_ImportModule("my_module");
      Guard module_guard(module);
      return PyObject_GetAttrString(module, "ExpressionTree");
    }
    
    void VisitTree(PyObject* py_tree) throw (Python_exception)
    {
      PyObject *cls = GetExpressionTreeClass();
      Guard cls_guard(cls);
    
      PyObject* list = PyObject_GetAttrString(py_tree, "children");
      if (!list && PyErr_ExceptionMatches(PyExc_AttributeError)) {
        PyErr_Clear();  // hasattr does this exact check
        return;
      }
      Guard list_guard(list);
    
      Py_ssize_t size = PyList_Size(list);
      for (Py_ssize_t i = 0; i < size; i++) {
        PyObject* child = PyList_GetItem(list, i);
        Py_XINCREF(child);
        Guard child_guard(child);
    
        // check if child is class instance or number (terminal)
        if (PyInt_Check(child) || PyLong_Check(child) || PyString_Check(child)) 
          ; // terminal - do nothing for now
        else if (PyObject_IsInstance(child, cls))
          VisitTree(child);
        else {
          PyErr_Format(PyExc_TypeError, "unrecognized %s object", Py_TYPE(child)->tp_name);
          throw Python_exception("unrecognized object from python");
        }
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm making a simple page using Google Maps API 3. My first. One marker
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.