mardi 28 mars 2017

Correct way to pass python object to c++ and then pack to python in callback using Boost

I have a scenario where I want to register a function in python to get called whenever a function is called in c++ and pass it a "cookie" object. This cookie can be any python object.

Python:

cookie = { "result" : True}
pythonModule.register_callback(self.log_callback, cookie)
self.assertEqual(6, len(cookie))

CPP:

boost::python::object g_logCallback;
boost::python::object g_logCookie;
void RegisterCallback(boost::python::object callback, boost::python::object cookie)
{
    g_logCallback= callback;
    g_logCookie= cookie;
}

bool LogCallback(const char* condition, const char* file, unsigned int line, int tag, const char* message)
{
    return g_logCallback(g_logCookie, condition, file, line, tag, message);
}

Python:

def log_callback(self, cookie, condition, file, line, tag, message):
    cookie["condition"] = condition
    cookie["file"] = file
    cookie["line"] = line
    cookie["tag"] = tag
    cookie["message"] = message

    return cookie["result"]

This code seems to work fine at first appearance. The callback gets called successfully. It has my dictionary with the contents and after the callback is done the original cookie object I passed in has the new contents. Perfect.

However it crashes when the program is done executing with a python decref error. Does anyone know the correct way I should be passing these objects and handling them?

Aucun commentaire:

Enregistrer un commentaire