1

I want to create a Thread instance from C++, with target=entity passed into the constructor, where entity is a boost::python::object, as this Python code is showing:

pythread = Thread(target=entity)

I saw this SO post and came up with this code. It throws an unhandled exception on the line object pythread = .... How can I do this?

void start(boost::python::object entity){
    using namespace boost::python;
    object main_module = import("__main__");
    object global = main_module.attr("__dict__");

    exec("from threading import Thread", global, global);

    dict kw;
    kw["target"] = entity.attr("start");

    object pythread = main_module.attr("Thread").attr("__init__"); //exception here

    PyObject* c_retval = PyObject_Call(pythread.ptr(), NULL, kw.ptr());

    object t = object(handle<>(c_retval));
    t.attr("start")();
}

Edit: Since Python's Thread object is defined as Thread(group=None, target=None, ...), the following code should work to pass in the correct argument:

object pythread = main_module.attr("Thread")(object(),entity.attr("start"));

However, passing entity.attr("Start") results in an error (no to_python converter). That is a problem for another SO post.

Community
  • 1
  • 1
  • You could try `.def` instead of `.attr` – sushant Jan 12 '16 at 10:21
  • Where? I thought def was used to expose functions - entity.start definitely does already exist, or it would print an error in the python console (which it doesn't). `object::def` does not return `object`. – Samuel SILVESTER Jan 13 '16 at 18:23

0 Answers0