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 !
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 .
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 .
#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;
}
give the thumbs-up
Collection
forward
A wave , Bloggers also support making exclusive dynamic wallpapers for iron fans ~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 !