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 !
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 :
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 :
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 .
#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;
}
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 !