2

I want to do something like this:

Py_Initialize();
PyRun_SimpleString("d = 0.97");
float a = ? // how to get value of d by its name?
Py_Finalize();

Is there a simple way to do this?

IzZy
  • 364
  • 3
  • 16
  • 1
    I'm not 100% sure, but I think that `d` ends up in the `__main__` module and you can use `PyModule_GetDict` to get its namespace `dict`. – tdelaney Aug 08 '20 at 15:43
  • `PyModule_GetDict` expect `*PyObject` as an argument, I have no idea how to use it. – IzZy Aug 08 '20 at 16:52

2 Answers2

1

PyRun_SimpleString will not help AFAIK.

Use PyRun_String instead of PyRun_SimpleString which returns an object a pointer to a PyObject. But this would not be very (simple) as mentioned by your question

Shadi Naif
  • 184
  • 9
  • I used `PyRun_SimpleString` only to initialize variable. I expect something like `PyGet_Float("var_name")` (i made it up), but i don't know if something like this exist. – IzZy Aug 08 '20 at 15:39
1

As said tdelaney, "d ends up in the __main__ module". So the best solution I find is

Py_Initialize();
PyRun_SimpleString("d = 0.97");
PyObject *mainModule = PyImport_AddModule("__main__");
PyObject *var = PyObject_GetAttrString(mainModule, "d");
float a = PyFloat_AsDouble(var);
Py_Finalize();

Not as simple as I expected, but acceptable and it works.

IzZy
  • 364
  • 3
  • 16