Jul-31-2022, 07:13 PM
I was using the sample code as base and trying to return a string from the func.
mainly it seem to fail on:
str = PyUnicode_AsEncodedString(result, "utf-8", "~I~");
the returned str object is NULL
mainly it seem to fail on:
str = PyUnicode_AsEncodedString(result, "utf-8", "~I~");
the returned str object is NULL
int main() { const char* spamclass = R""""( class Spam: def func(self): if __name__ == '__main__': print('called in __main__') return "Completed" else: print('called out of __main__') return "Skipped" )""""; PyObject* mainmod, * Spam, * spam, * meth, * result, * repr, *str; const char* s; Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print('Today is', ctime(time()))\n"); PyRun_SimpleString( spamclass ); mainmod = PyImport_ImportModule("__main__"); Spam = PyObject_GetAttrString(mainmod, "Spam"); spam = PyObject_CallObject(Spam, NULL); meth = PyObject_GetAttrString(spam, "func"); result = PyObject_CallObject(meth, NULL); if (!PyUnicode_CheckExact(result)) { repr = PyObject_Repr(result); str = PyUnicode_AsEncodedString(repr, "utf-8", "~I~"); s = PyBytes_AS_STRING(str); cout << "response from python: " << s << endl; } else { str = PyUnicode_AsEncodedString(result, "utf-8", "~I~"); s = PyBytes_AS_STRING(str); cout << "response from python: " << s << endl; } if (Py_FinalizeEx() < 0) { exit(120); } return 0; }