[C++-sig] Re: compile errors with embedding example from tutorial

Faheem Mitha faheem at email.unc.edu
Thu Jul 1 22:19:37 CEST 2004


On Thu, 1 Jul 2004 09:05:32 -0700, Graeme Lufkin
<graeme.lufkin at gmail.com> wrote:

>     I've had similar problems, and have slogged my way to figuring
> them out.  The tutorial is wrong, at least on gcc 3.2.3.
>   Here's what you want:  After calling Py_Initialize(), you should get
> the Python main namespace object by doing:
>
> handle<> main_module(borrowed( PyImport_AddModule("__main__") ));
> dict main_namespace = extract<dict>(PyModule_GetDict(main_module.get()));

I think this should be main_module.ptr() since main_module is an object.

> The first line gets a pointer to the '__main__' module object and
> stores it as a borrowed reference in a handle.  The second line gets
> the dictionary of the '__main__' module and puts it in a dict C++
> object.  You should now use this dictionary as the globals and locals
> of PyRun_* functions that you call.  For example:
> handle<> unused(PyRun_String("import yourModuleNameHere",
> Py_file_input, main_namespace.ptr(), main_namespace.ptr()));
> handle<> unused2(PyRun_String("f = file('test_output', 'w')",
> Py_file_input, main_namespace.ptr(), main_namespace.ptr()));
>
> You need to name the handle<> objects, even though you don't use them.
>  If not, while you may think you're creating an anonymous temporary
> that will immediately get destructed, the compiler thinks you're
> declaring a function and gets very confused.
>
> Hope this helps.  As usual, I invoke the great spirit of Dave Abrahams
> to correct/clarify anything I've said that's not quite right or
> misleading.  Good luck

I'm trying with

******************************************************************************
#include <boost/python.hpp>
using namespace boost::python;

void foo()
{
  Py_Initialize();
  
  object main_module =
object(handle<>(borrowed(PyImport_AddModule("__main__"))));

  dict main_namespace = extract<dict>(PyModule_GetDict(main_module.ptr()));

  handle<> unused(PyRun_String("hello = file('hello.txt', 'w')\n"
			  "hello.write('Hello world!')\n"
			  "hello.close()", Py_file_input,
			  main_namespace.ptr(),main_namespace.ptr()));
    Py_Finalize();
}

BOOST_PYTHON_MODULE(embed)
{
  def("foo",foo);
}
*******************************************************************************

This compiles, but I get the same error as before, namely

NameError: name 'file' is not defined

Does this work correctly for you? I'm wondering if there is some issue
with my compiler flags. I'm trying to get Boost.Build to work but
there are some linking problems.

                                                           Faheem.





More information about the Cplusplus-sig mailing list