[C++-sig] problem embedding python - very simple example

Cory Riddell cory at codeware.com
Tue Nov 6 20:40:18 CET 2012


I downloaded and installed the 32-bit version of Python 3.3. I
downloaded and compiled boost-1.52.0. I've been able to build and run
the tutorial Python extension but haven't been able to get anything but
the most trivial example of embedding to work.

My code (which compiles with no warnings):

  #include <boost/python.hpp>

  using namespace boost::python;

  int main()
  {
    Py_Initialize();
    object main_module = import("__main__");
    object main_namespace = main_module.attr("__dict__");

    exec("print('hello')\n", main_namespace);
    exec("print('world')\n", main_namespace);
    exec("f = file('hello.txt', 'w')\n", main_namespace);

    return 0;
  }

It prints "hello\nworld\n" then throws an exception executing the line
that creates the hello.txt file:
  First-chance exception at 0x755ac41f in Test.exe: Microsoft C++
exception: boost::python::error_already_set at memory location 0x0039fb60..
  Unhandled exception at 0x773915de (ntdll.dll) in Test.exe: Microsoft
C++ exception: boost::python::error_already_set at memory location
0x0039fb60..

In the exec method, the exception is being thrown when result comes back
as null:
  PyObject* result = PyRun_String(s, Py_file_input, global.ptr(),
local.ptr());
  if (!result) throw_error_already_set();

I'm using VS2010SP1 on Windows7 which I believe is what Python 3.3 is
built with. I'm dynamically linking against boost.

Any suggestions?



More information about the Cplusplus-sig mailing list