Max Frai
Max Frai

Reputation: 64266

Python initialization segfault

I'm building app with boost.python. I have some singleton class named ScriptsManager, it has function initPython which does:

mMainModule = bp::import("__main__");
mMainNamespace = bp::import("__dict__");

bp::object ignored = bp::exec("hello = file('hello.txt', 'w')\n"
                  "hello.write('Hello world!')\n"
                  "hello.close()", mMainNamespace);

both mMainModule, mMainNamespace are boost::python::object.

So, when I start application, I get:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) bt
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff5d5efd9 in PyEval_GetGlobals () from /usr/lib/libpython2.7.so.1.0
#2  0x00007ffff5d79113 in PyImport_Import () from /usr/lib/libpython2.7.so.1.0
#3  0x00007ffff5d7935c in PyImport_ImportModule () from /usr/lib/libpython2.7.so.1.0
#4  0x00007ffff5a6d8bd in boost::python::import(boost::python::str) () from /usr/lib/libboost_python.so.1.46.0
#5  0x0000000000510b1b in ScriptsManager::initPython (this=0x7b6850) at /home/ockonal/Workspace/Themisto/src/Core/ScriptsManager.cpp:24
#6  0x0000000000547650 in Application::main (args=...) at /home/ockonal/Workspace/Themisto/src/main.cpp:60
#7  0x00007ffff4ebbf86 in main () from /usr/lib/libclan22App-2.2.so.1
#8  0x00007ffff24c4dcd in __libc_start_main () from /lib/libc.so.6
#9  0x00000000004c9769 in _start ()

What could be wrong here?


UPD1

When I call Py_Initialize() before bp::import I get:

terminate called after throwing an instance of 'boost::python::error_already_set'


UPD2

Seems that problem was in code:

mMainNamespace = bp::import("__dict__");

The result code is:

Py_Initialize();
mMainModule = bp::import("__main__");
mMainNamespace = mMainModule.attr("__dict__");

I'm not sure it's right.


UPD3

Yep, 2-nd update works. So strange, mMainNamespace = bp::import("__dict__") is written in official boost docs.

Upvotes: 5

Views: 3116

Answers (1)

filmor
filmor

Reputation: 32212

I think what you want is the following:

int main (int argc, char** argv)
{
    try
    {
        // If you're going to use threads: PyEval_InitThreads();
        Py_Initialize();
        PySys_SetArgv(argc, argv);

        bp::object mMainModule = bp::import('__main__');
        bp::object mMainNamespace = mMainModule.attr('__dict__');

        bp::object ignored = bp::exec("hello = file('hello.txt', 'w')\n"
              "hello.write('Hello world!')\n"
              "hello.close()", mMainNamespace);
   }
   catch (bp::error_already_set const&)
   {
        PyErr_Print();
   }
}

Py_Initialize() is necessary, the try { ... } catch () { ... }-block produces a Python error message like the one you would get from the interpreter and bp::import only works for modules, not for attributes of imported modules :-)

Upvotes: 3

Related Questions