简体   繁体   中英

How to run a Python function from a Qt C++ project?

I've followed some tutorials and advice, I've even ran one function without problems, using PyRun_SimpleString . I have a file called tomograph.py with a makeFiles(path,alpha,n,l) function I want to execute, and a my_fun(x) function that I managed to run (as I already mentioned).

This is what I do in my Qt C++ project

Py_Initialize();

PyObject* moduleString = PyString_FromString((char*)"tomograph");
PyObject* module = PyImport_Import(moduleString);

PyObject* function = PyObject_GetAttrString(module,(char*)"makeFiles");
PyObject* args = PyTuple_Pack(4,filename,alpha,n,l);

//PyRun_SimpleString("my_fun(5)");

PyObject* myResult = PyObject_CallObject(function,args);

Py_Finalize();

When I run this code I get a segmentation fault at

PyObject* function = PyObject_GetAttrString(module,(char*)"makeFiles");

What am I doing wrong?

Setting PYTHONPATH to the working directory and putting the .py file in the build folder should do the trick:

setenv("PYTHONPATH",".",1);
Py_Initialize();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM