程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python & c++ mixed call programming comprehensive practice -17c++ calls Python functions, passes list parameters and gets the return

編輯:Python

author : Empty bad uncle
Blog :https://xuhss.com

The breakfast shop won't be open till night , The people who want to eat have already come !

C++ call python Function transfer list Parameter and get return

One 、C++ call python Parameterless return function

stay test.py Add functions to :

print('test.py')
def Main():
print("Python Main")

stay c++ This function is called

 // C++ call Python function 
PyObject* Main = PyObject_GetAttrString(m, "Main");
if (Main && PyCallable_Check(Main)) {

// Function objects and parameters Returns the object 
if (!PyObject_CallObject(Main, 0))
{

throw exception("PyObject_CallObject Failed");
}
}
Py_XDECREF(Main);

Operation :

You can see the successful call .

Two 、C++ call python Functions with parameters and return values

stay test.py Add functions to TestFun

print('test.py')
def Main():
print("Python Main")
def TestFun(lis):
print("In Python", lis)
return [1,2,3,4,5,6,7,8,9,10]

stay C++ Call in

 // C++ call Python function 
PyObject* Main = PyObject_GetAttrString(m, "Main");
if (Main && PyCallable_Check(Main)) {

// Function objects and parameters Returns the object 
if (!PyObject_CallObject(Main, 0))
{

throw exception("PyObject_CallObject Failed");
}
}
Py_XDECREF(Main);
// c++ call Python Function of list Parameters and list Return value 
PyObject* TestFun = PyObject_GetAttrString(m, "TestFun");
if (TestFun && PyCallable_Check(TestFun)) {

// Parameter preparation The parameter variable is tuple
PyObject *args = PyTuple_New(1); // The argument is a tuple Only tuple is a parameter 
// Delivered list object 
PyObject *lis = PyList_New(0);
for (int i = 0; i < 5; i++)
PyList_Append(lis, PyLong_FromLong(i + 100));
// take list Write to the tuple parameter list 
PyTuple_SetItem(args, 0, lis);
// Return values of function objects and parameters 
PyObject* re = PyObject_CallObject(TestFun, args);
Py_XDECREF(args); // lis Also in the args Medium destruction 
// Process return value 
if (re)
{

cout << "PyObject_CallObject return" << endl;
int size = PyList_Size(re);
for (int i = 0; i < size; i++)
{

PyObject *val = PyList_GetItem(re, i);
if (!val)
continue;
printf("[%d]", PyLong_AsLong(val));
}
Py_XDECREF(re);
}
}
Py_XDECREF(TestFun);

It turns out

You can see that the call was successful , Output the passed list , The return value can also be output .

3、 ... and 、 The complete call code is posted below

#include <iostream>
#include <Python.h>
#include <exception>
using namespace std;
int main(int argc, char*argv[])
{

cout << "C++ call Python" << endl;
// Set up Python Of Home route 
Py_SetPythonHome(L"./");
// Python Initialize the interpreter 
Py_Initialize();
PyObject *m = NULL; // The main module 
try
{

int re = 0;
// perform Python Script 
re = PyRun_SimpleString("print('Hello world!')");
re = PyRun_SimpleString("print(\"__name__ = \", __name__)");
// perform Python file 
char* filename = "test.py";
FILE * fp = fopen(filename, "r");
if (!fp)
{

throw exception("open file failed");
}
PyRun_AnyFile(fp, filename);
if (re != 0)
{

PyErr_Print();
throw exception("PyRun_AnyFile failed");
}
// Get main module 
PyObject *key = PyUnicode_FromString("__main__");
m = PyImport_GetModule(key); // Do not clean parameters , It needs to be cleaned by hand 
Py_XDECREF(key);
// 2-1 call python The variable of python Make configuration file 
//con = {

// "width":1920,
// "heigth" : 1080,
// "title" : "C++ call Python"
//}
{

// Get objects by module and name ( Objects can be variables 、 Functions and classes )
PyObject* conf = PyObject_GetAttrString(m, "conf");
if (!conf) {

throw exception("conf noe find!");
}
PyObject *key = PyUnicode_FromString("width");
int width = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
key = PyUnicode_FromString("height");
int height = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
key = PyUnicode_FromString("title");
wchar_t title[1024] = {
 0 };
int size = PyUnicode_AsWideChar(PyDict_GetItem(conf, key), title, 1023);
Py_XDECREF(key);
printf("width=%d height=%d \n", width, height);
wprintf(L"title=%s\n", title);
Py_XDECREF(conf);
}
{

// Get class 
PyObject* TypePy = PyObject_GetAttrString(m, "TypePy");
if (!TypePy) {

throw exception("TypePy noe find!");
}
// Instantiate objects It is equivalent to calling the constructor __init__ Pass arguments to the constructor NULL
PyObject *obj = PyObject_CallObject(TypePy, NULL);
if (!obj) {

throw exception("obj not Create!");
}
// Calling class member functions i(int) s(string)
PyObject *re = PyObject_CallMethod(obj, "test", "is", 2001, "c Para2");
cout << "PyObject_CallMethod return" << PyLong_AsLong(re) << endl;
Py_XDECREF(re);
// Access member variables 
PyObject* var = PyObject_GetAttrString(obj, "id");
cout << "TypePy.id=" << PyLong_AsLong(var) << endl;
Py_XDECREF(var);
Py_XDECREF(obj);
Py_XDECREF(TypePy);
}
{

// C++ call Python function 
PyObject* Main = PyObject_GetAttrString(m, "Main");
if (Main && PyCallable_Check(Main)) {

// Function objects and parameters Returns the object 
if (!PyObject_CallObject(Main, 0))
{

throw exception("PyObject_CallObject Failed");
}
}
Py_XDECREF(Main);
// c++ call Python Function of list Parameters and list Return value 
PyObject* TestFun = PyObject_GetAttrString(m, "TestFun");
if (TestFun && PyCallable_Check(TestFun)) {

// Parameter preparation The parameter variable is tuple
PyObject *args = PyTuple_New(1); // The argument is a tuple Only tuple is a parameter 
// Delivered list object 
PyObject *lis = PyList_New(0);
for (int i = 0; i < 5; i++)
PyList_Append(lis, PyLong_FromLong(i + 100));
// take list Write to the tuple parameter list 
PyTuple_SetItem(args, 0, lis);
// Return values of function objects and parameters 
PyObject* re = PyObject_CallObject(TestFun, args);
Py_XDECREF(args); // lis Also in the args Medium destruction 
// Process return value 
if (re)
{

cout << "PyObject_CallObject return" << endl;
int size = PyList_Size(re);
for (int i = 0; i < size; i++)
{

PyObject *val = PyList_GetItem(re, i);
if (!val)
continue;
printf("[%d]", PyLong_AsLong(val));
}
Py_XDECREF(re);
}
}
Py_XDECREF(TestFun);
}
Py_XDECREF(m);
// clear python
Py_Finalize();
}
catch (const std::exception&ex)
{

if (PyErr_Occurred())
PyErr_Print();
cout << ex.what() << endl;// clear python
Py_XDECREF(m);
Py_Finalize();
}
getchar();
return 0;
}

Four 、 summary

  • This article USES the C++ call python Function transfer list Parameter and get return .
  • If you think the article is useful to you , Remember give the thumbs-up Collection forward A wave , Bloggers also support making exclusive dynamic wallpapers for iron fans ~

Share high-quality articles in previous periods

  • C++ QT combination FFmpeg Actual development of video player -01 Environment installation and project deployment
  • solve QT problem : function qmake:Project ERROR: Cannot run compiler ‘cl‘. Output:
  • Resolve installation QT after MSVC2015 64bit No compiler and debugger issues with configuration
  • Qt Kit tips in no complier set in kit and no debugger, The yellow exclamation mark appears and the problem is solved (MSVC2017)
  • Python+selenium automation - Realize automatic import 、 Upload external files ( Don't pop up windows window )

High quality tutorial sharing

  • If you don't enjoy reading the article , You can come to my other special column Take a look ~
  • For example, the following columns :Python Actual wechat ordering applet 、Python Quantitative trading practice 、C++ QT Practical projects and Algorithm learning column
  • You can learn more about C++/Python Relevant contents of ! Directly click on the color font below to jump !
Learning route guidance ( Click unlock ) Knowledge orientation Crowd positioning 🧡 Python Actual wechat ordering applet 🧡 Progressive class This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system .Python Quantitative trading practice beginner Take you hand in hand to create an easy to expand 、 More secure 、 More efficient Quantitative trading System ️ C++ QT combination FFmpeg Actual development of video player ️ The difficulty is high Sharing learning QT Finished video player source code , We need to have a solid C++ knowledge ! A community of 90000 game lovers Help each other / Blow water 90000 game lovers community , Chat and help each other , White whoring prize Python Zero basis to introduction Python beginner For small partners who have not been systematically studied , The core purpose is to enable us to learn quickly Python Knowledge to get started

Data white whoring , reminder

Follow the card below to get more programming knowledge immediately , Including various language learning materials , Thousands of sets PPT Templates and various game source materials and so on . More information can be viewed by yourself !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved