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

Python & c++ mixed call programming comprehensive practice -19c++ transfer functions and custom modules to Python

編輯: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++ to python Transfer functions and custom modules

One 、 Transfer function

python Terminal test.py Add a function call :

stay C++ First, you need to add a function pointer

static PyObject *test_cfun(PyObject *self, PyObject *args)
{
cout << "in c++ test_cfun function" << endl;
Py_RETURN_TRUE;
}

Then add the definition of the function : And function calls :

// to Python Transfer function
PyMethodDef cfuns[] = {
{"test_cfun", test_cfun, METH_VARARGS, 0},
{NULL}
};
PyModule_AddFunctions(m, cfuns);

Run code :

Two 、 Read python Module and give python Main module transfer module

2.1 Delivery practice

Define a python modular testmod.py:

print("Test Mod In python")
def testmod():
print("testmod function in testmod.py")

stay c++ Import module , And add this module to the main module :

 // to python Transfer module
// Read module ( The script file acts directly as a module )
PyObject *testmod = PyImport_ImportModule("testmod"); // amount to python Inside import testmod
if (!testmod)
{
throw exception("PyImport_ImportModule testmod failed");
}
// Pass the module to python The main module of
PyModule_AddObject(m, "testmod", testmod);

stay test.py The... Passed in by the call in testmod Function of module :

# c The module passed through
testmod.testmod()

function :

2.2 Use of transfer module

Pass the module to python The main module of , You can be in c++ Import module , This gives the user the illusion that my script can bring many modules , There is no need to introduce modules every time . You can use it directly .

3、 ... and 、 Complete code

#include <iostream>
#include <Python.h>
#include <exception>
using namespace std;
static PyObject *test_cfun(PyObject *self, PyObject *args)
{
cout << "in c++ test_cfun function" << endl;
Py_RETURN_TRUE;
}
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__)");
// 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);
// The transfer position should be at python Before code calls
// to python Pass on Variable 、 function 、 class 、 modular ( Read a python The module is passed to the main module )
// Passing variables ( It can only be transmitted to the main module __main__)
PyRun_SimpleString("a=888");
// Support to pass other non _main__ modular , Space transfer to python management
PyObject_SetAttrString(m, "count", PyLong_FromLong(777));
// to Python Transfer function
PyMethodDef cfuns[] = {
{"test_cfun", test_cfun, METH_VARARGS, 0},
{NULL}
};
PyModule_AddFunctions(m, cfuns);
// to python Transfer module
// Read module ( The script file acts directly as a module )
PyObject *testmod = PyImport_ImportModule("testmod"); // amount to python Inside import testmod
if (!testmod)
{
throw exception("PyImport_ImportModule testmod failed");
}
// Pass the module to python The main module of
PyModule_AddObject(m, "testmod", testmod);
// 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");
}
// 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)
{
cout << ex.what() << endl;// clear python
Py_XDECREF(m);
Py_Finalize();
}
getchar();
return 0;
}

Four 、 summary

  • This article explains c++ to python Transfer functions and custom modules .
  • 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