I am trying to call some python code from my c++ app but i cannot for the love of god get PyImport_Import to import the module/file from the working dir of the app
int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue;
int i;
const auto f = fopen("test.txt", "w");
if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}
PyConfig conf;
Py_Initialize();
PyObject* sys = PySys_GetObject("path");
//PyList_Append(sys, PyUnicode_FromString("./"));
for(Py_ssize_t idx = 0; idx < PyList_Size(sys); idx++)
{
PyObject* item = PyList_GET_ITEM(sys, idx);
wchar_t str[1000];
PyUnicode_AsWideChar(item, str, 1000);
std::wcout << str << "\n";
}
pName = PyUnicode_DecodeFSDefault(argv[1]);
/* Error checking of pName left out */
std::cout << "starting..22.";
pModule = PyImport_Import(pName);
PyErr_Print();
PyObject_Print(pModule, f, Py_PRINT_RAW);
Py_DECREF(pName);
std::cout << "starting...";
if (pModule != NULL) {
std::cout << "1\n";
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
std::cout << "2\n";
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
std::cout << "3\n";
pValue = PyLong_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
std::cout << "4\n";
printf("Result of call: %ld\n", PyLong_AsLong(pValue));
Py_DECREF(pValue);
}
else {
std::cout << "5\n";
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else {
std::cout << "6\n";
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
if (Py_FinalizeEx() < 0) {
return 120;
}
return 0;
}
As you can see i’ve added multiple log points to maybe get some info, the important one being the printing of sys.path and the pModule
the output of them being
PS C:\dev\SFW\out\tests> .\SFW_unit_test.exe test test_func
C:\Users\Iulian\AppData\Local\Programs\Python\Python313\python313.zip
C:\Users\Iulian\AppData\Local\Programs\Python\Python313\DLLs
C:\Users\Iulian\AppData\Local\Programs\Python\Python313\Lib
C:\dev\SFW\out\tests
C:\Users\Iulian\AppData\Local\Programs\Python\Python313
C:\Users\Iulian\AppData\Local\Programs\Python\Python313\Lib\site-packages
starting..22.starting...1
6
AttributeError: module 'test' has no attribute 'test_func'
Cannot find function "test_func"
And
<module 'test' from 'C:\\Users\\Iulian\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\test\\__init__.py'>
the test.py file is in the same directory as the executable and contains
def test_func():
print("hello from function")