1. 程式人生 > 其它 >c/c++ 呼叫python程式例項(QT)

c/c++ 呼叫python程式例項(QT)

c/c++ 呼叫python程式例項(QT)

參考:Qtcreator中C++呼叫python方法 : https://blog.csdn.net/alxe_made/article/details/83382159/

C++呼叫Python淺析:

https://blog.csdn.net/magictong/article/details/8947892?spm=1035.2023.3001.6557&utm_medium=distribute.pc_relevant_bbs_down.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-5.nonecase&depth_1-utm_source=distribute.pc_relevant_bbs_down.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-5.nonecase

test.c

#include <stdio.h>

#include<Python.h>

int main()

{

printf("Hello World!\n");

//for python call

Py_Initialize();

if(!Py_IsInitialized()){

return -1;

}

PyObject* pyModule = PyImport_ImportModule("test_py");

if(pyModule == NULL) {

printf("Can't open python file!\n");

return -1;

}

PyObject* pyFunhello = PyObject_GetAttrString(pyModule, "hello");

if(pyFunhello == NULL) {

printf("Get function hello failed\n");

return -1;

}

PyObject_CallFunction(pyFunhello, NULL);

Py_Finalize();

return 0;

}

test_py.py

#!/usr/bin/env python

#_*_ coding: utf-8 _*_

def hello():

print("hello world form python\n")


qt 工程檔案:

TEMPLATE = app

CONFIG += console

CONFIG -= app_bundle

CONFIG -= qt

INCLUDEPATH +=C:\Users\y00430891\AppData\Local\Programs\Python\Python39\include\

LIBS += -LC:\Users\y00430891\AppData\Local\Programs\Python\Python39\libs\

-l_tkinter\

-lpython3\

-lpython39

SOURCES += \

test.c

DISTFILES += \

test_py.py