3

Is there a way to get object reference of an existing object, in an embedded Python code?

In other words: If an object called 'obj' already exist (created by a script), and I need to "convert" it to a PyObject* reference, is there a function like: PyObject *getObjectReference(char *name) ?

EDIT: As a way of example, let's say I import some module in one part of the code, by using

PyRun_SimpleString("var = 1");

(Or as well it could be an external script defining the same variable)

Now, in another point of the code I want to get that variable. I'm looking for something like

PyObject *varPy = PyObject_GetGlobalObject("var");

"reading a global variable of python in c" partially answer my question by implicitly saying that it is not possible to retrieve a global defined variable without having a reference to the module that created it. Is this correct?

Community
  • 1
  • 1
FedFranz
  • 529
  • 1
  • 5
  • 15
  • 1
    Could you add some more code showing what you're trying to do? – tynn Oct 24 '16 at 22:00
  • In response to your edit: if you know the name of the module the variable is in you can import it to get reference to the module (there's no problem with importing a module that is already imported). – DavidW Oct 25 '16 at 10:30
  • Plus, if you look up the documentation for `PyRun_SimpleString` it tells you the module it's run in is `__main__` – DavidW Oct 25 '16 at 10:45
  • Thanks for the suggestions DavidW. The variable is not made by any module, but by the main script. I thought it could be retrievable from the __main__, but in the other question ("reading a global variable...") the guy says it didn't work for him (maybe because its variable was defined within a script?). I will give it a try! – FedFranz Oct 25 '16 at 12:14
  • Works like a charm! Thanks again. I will write a full answer to my question for further reference. – FedFranz Oct 25 '16 at 12:50

1 Answers1

1

Assembling the info gathered from DavidW (thanks for you help), by the reading a global variable of python in c and a few tests I made.

To get the reference to an already loaded module, use:

PyImport_AddModule("module_name");

In order to get the reference to a globally defined variable, import the main module and get the reference by name:

PyObject *mainModule = PyImport_AddModule("__main__");
PyObject *var = PyObject_GetAttrString(mainModule, "var_name");

If the variable is defined within a different module/script, then it will be visible only in that module (not globally). So you will have to change "main" with the name of that specific module.

Community
  • 1
  • 1
FedFranz
  • 529
  • 1
  • 5
  • 15