| 27 | } |
| 28 | |
| 29 | PyObject* findClass(const std::string& resources, const std::string& moduleName) |
| 30 | { |
| 31 | // Initialize the Python interpreter |
| 32 | std::string filename = resources + "/" + moduleName + ".py"; |
| 33 | std::string deepestFile; |
| 34 | int deepestChain = 0; |
| 35 | |
| 36 | // Read and execute the Python file |
| 37 | std::ifstream file; |
| 38 | file.open(filename); |
| 39 | |
| 40 | if (!file.is_open()) { |
| 41 | return nullptr; |
| 42 | } |
| 43 | |
| 44 | std::stringstream fileContents; |
| 45 | std::string line; |
| 46 | |
| 47 | while (std::getline(file, line)) { |
| 48 | fileContents << line << "\n"; |
| 49 | } |
| 50 | |
| 51 | // Compile python code so classes are added to the namespace |
| 52 | PyObject* pyModule = PyImport_ImportModule(moduleName.c_str()); |
| 53 | |
| 54 | if (pyModule == nullptr) { |
| 55 | return nullptr; |
| 56 | } |
| 57 | PyObject* pGlobals = PyModule_GetDict(pyModule); |
| 58 | PyObject* pLocals = PyDict_New(); |
| 59 | PyObject* pCode = Py_CompileString(fileContents.str().c_str(), moduleName.c_str(), Py_file_input); |
| 60 | |
| 61 | if (pCode != nullptr) { |
| 62 | PyObject* pResult = PyEval_EvalCode(pCode, pGlobals, pLocals); |
| 63 | Py_XDECREF(pResult); |
| 64 | } else { |
| 65 | PyErr_Print(); // Handle compilation error |
| 66 | Py_Finalize(); |
| 67 | Py_DECREF(pGlobals); |
| 68 | Py_DECREF(pyModule); |
| 69 | Py_DECREF(pLocals); |
| 70 | Py_DECREF(pCode); |
| 71 | file.close(); |
| 72 | return nullptr; |
| 73 | } |
| 74 | |
| 75 | fileContents.clear(); |
| 76 | PyObject *key, *value; |
| 77 | Py_ssize_t pos = 0; |
| 78 | |
| 79 | while (PyDict_Next(pLocals, &pos, &key, &value)) { |
| 80 | // Check if element in namespace is a class |
| 81 | if (!PyType_Check(value)) { |
| 82 | continue; |
| 83 | } |
| 84 | |
| 85 | PyObject* pMroAttribute = PyObject_GetAttrString(value, "__mro__"); |
| 86 |
no test coverage detected