[C++-sig] Beginner - PyObject_CallObject fails because imported module is not recognized

Stefan Seefeld stefan at seefeld.name
Wed Jan 6 08:57:51 EST 2016


Hi Christian,

for the sake of simplicity I have transcribed your example to pure
Python, which also exhibits the same behavior:

#!/usr/bin/env python

script = """import pprint
import sys
counter= 0
def onInitialize(ctxt):
  global counter
  counter+=1
  pprint.pprint(sys.path)
  return counter"""


code = compile(script, "<input>", 'exec')
globals = {}
locals = {}
eval(code, globals, locals)
callback = locals['onInitialize']
callback(())


The problem is that, while the "globals" object is shared between the
module and the function, the "locals" is not (i.e., the function gets
its own local namespace, which is distinct from the local namespace of
the module).
To get what you want you may simply replace the "locals" argument in the
"eval" call above by "globals" (or simply put "None" there, which has
the same effect.

In any case, I'd recommend you rewrite your code using the Boost.Python
bindings; it will become much more compact and readable, and will look
very much like the Python code above. :-)

Regards,
        Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list