Skip to content

Commit ad94a0a

Browse files
committed
Fix loading of the cppyy python module.
import cppyy has a similar effect to __import__('cppyy', globals(), locals(), [], 0). To model in the C API we need to assign to the cppyy global. That is, set the cppyy attribute on the __main__ module.
1 parent 2bc792a commit ad94a0a

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

src/xmagics/pythonexec.cpp

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,11 @@ namespace xcpp {
3131
static PyObject *gMainDict = 0;
3232

3333
void pythonexec::startup() {
34-
if (gMainDict)
34+
static bool isInitialized = false;
35+
if (isInitialized)
3536
return;
3637

3738
Py_Initialize();
38-
gMainDict = PyModule_GetDict(PyImport_AddModule(("__main__")));
39-
Py_INCREF(gMainDict);
40-
if (!gMainDict)
41-
printf("Could not add module __main__");
4239

4340
PyRun_SimpleString("import sys\nprint(sys.path)");
4441

@@ -50,19 +47,30 @@ void pythonexec::startup() {
5047
return; // Handle import error as needed
5148
}
5249

53-
// Retrieve the dictionary of cppyy module
54-
PyObject* cppyyDict = PyModule_GetDict(cppyyModule);
55-
Py_DECREF(cppyyModule);
56-
if (!cppyyDict) {
57-
PyErr_Print();
58-
Py_Finalize();
59-
return; // Handle retrieval error as needed
60-
}
61-
62-
// Add cppyyDict to gMainDict (if needed for further usage)
63-
PyDict_Update(gMainDict, cppyyDict);
64-
65-
Py_DECREF(cppyyDict);
50+
PyObject* mainModule = PyImport_AddModule("__main__");
51+
PyObject_SetAttrString(mainModule, "cppyy", cppyyModule);
52+
Py_XDECREF(cppyyModule);
53+
isInitialized = true;
54+
// gMainDict = PyModule_GetDict(mainModule);
55+
// Py_INCREF(gMainDict);
56+
// if (!gMainDict)
57+
// printf("Could not add module __main__");
58+
59+
60+
// // Retrieve the dictionary of cppyy module
61+
// PyObject* cppyyDict = PyModule_GetDict(cppyyModule);
62+
// Py_DECREF(cppyyModule);
63+
// if (!cppyyDict) {
64+
// PyErr_Print();
65+
// Py_Finalize();
66+
// return; // Handle retrieval error as needed
67+
// }
68+
69+
// // Add cppyyDict to gMainDict (if needed for further usage)
70+
// PyDict_Update(gMainDict, cppyyDict);
71+
72+
// Py_DECREF(cppyyDict);
73+
// PyRun_SimpleString("import cppyy");
6674
}
6775

6876
xoptions pythonexec::get_options() {

0 commit comments

Comments
 (0)