【发布时间】:2021-05-27 19:39:33
【问题描述】:
我需要从 qt c++ (qmake) 调用 python 并在它们之间共享数据。所以我写了这段代码但错误是合乎逻辑的,我的意思是没有错误但它意外停止。
我也用 python2.7 试过这个,但同样的错误。我想将 a 传递给 someFunction 函数并将其返回给 main.cpp
代码:
someFunction.py:(我把它放在项目的“Otherfile”部分)
def someFunction(a):
return a
main.cpp:
#include <Python.h>
#undef B0
#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
PyObject* myModuleString = PyUnicode_FromString((char*)"arbName");
PyObject* myModule = PyImport_Import(myModuleString);
PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"someFunction");
PyObject* args = Py_BuildValue("(d)", 2.0);
PyObject *myResult = PyObject_CallObject(myFunction, args);
qDebug() << "Hello World";
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
qmake:
QT += core gui
INCLUDEPATH = /usr/include/python3.8
LIBS += -lpython3.8
CLANG_INSTALL_DIR += usr/lib/clang/10/lib/linux
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
CONFIG += no_keywords
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
DISTFILES += \
someFunction.py
【问题讨论】:
标签: python qt cpython python-c-api