I am trying to use the Python 3.5 C API to execute some code that includes constructing a class. Specifically this:
class MyClass:
def test(self):
print('test')
MyClass().test()
The problem I have is that it errors like this:
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: __build_class__ not found
So somehow I need my module to include __build_class__, but I am not sure how (I guess that I would also miss other things you get by default when using Python too) - is there a way to include all this built-in stuff in my module?
Here is my code so far:
#include <Python.h>
int main(void)
{
int ret = 0;
PyObject *pValue, *pModule, *pGlobal, *pLocal;
Py_Initialize();
pGlobal = PyDict_New();
pModule = PyModule_New("mymod");
pLocal = PyModule_GetDict(pModule);
pValue = PyRun_String(
"class MyClass:\n\tdef test(self):\n\t\tprint('test')\n\nMyClass().test()",
Py_file_input,
pGlobal,
pLocal);
if (pValue == NULL) {
if (PyErr_Occurred()) {
PyErr_Print();
}
ret = 1;
} else {
Py_DECREF(pValue);
}
Py_Finalize();
return ret;
}
so pValue is NULL and it is calling PyErr_Print.