Hello,

I'm a bit new to boost::python and I've run into a strange
segmentation fault issue. I'm attempting to convert a dict object to a
boost::property_tree::ptree using the code below. I'm getting the
error when I attempt to access the input dict, with the following
stacktrace:

(gdb) bt
#0  0x00000001004d58df in PyObject_RichCompare ()
#1  0x00000001004d64e0 in PyObject_RichCompareBool ()
#2  0x00000001004cbf9d in lookdict ()
#3  0x00000001004cfa4f in dict_subscript ()
#4  0x00000001000c9cc5 in boost::python::api::getitem ()
#5  0x000000010000218b in boost::python::api::const_item_policies::get
(target=@0x7fff5fbff680, key=@0x7fff5fbff688) at object_items.hpp:68
#6  0x000000010000371b in
boost::python::api::proxy<boost::python::api::const_item_policies>::operator
boost::python::api::object (this=0x7fff5fbff680) at proxy.hpp:64
#7  0x0000000100000f56 in ptree_from_dict (d=@0x7fff5fbff6d0) at
test_ptree.cpp:55
#8  0x00000001000015fd in main () at test_ptree.cpp:104

Any help/advice would be greatly appreciated. The code below was
adapted from an existing github project, and I can't figure out what's
amiss.

Thanks,
Fred Baba

template<typename T>
bool try_set(boost::property_tree::ptree &pt, const std::string &key,
object &val) {
        extract<T> ex(val);
        if (ex.check()) {
                pt.put<T>(key, ex());
                return true;
        }
        return false;
}

boost::property_tree::ptree ptree_from_dict(const dict &d) {
        boost::property_tree::ptree pt;
        boost::python::list keys = d.keys();
        for (int i = 0; i < len(keys); ++i) {
                std::string key = extract<std::string>(keys[i]);
                object val = d[key];

                try_set<std::string>(pt, key, val)
                || try_set<long>(pt, key, val)
                || try_set<double>(pt, key, val);
        }
        return pt;
}

int main() {
        try {
                Py_Initialize();

                dict d;
                d["foo"] = 5;
                d["bar"] = "baz";

                object o = ptree_to_object(ptree());

                ptree p = ptree_from_dict(d);
                write_json(std::cout, p);

                Py_Finalize();
        } catch (error_already_set const&) {
                PyErr_Print();
        }
        return 0;
}
_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to