Python is a concise language in practical applications in computer languages. In practical applications, it can avoid inconvenience caused by many other languages, this article introduces how to embed C ++ into Python. If you understand this operation, you will get a better application in Python.
The following describes how to embed Python into C ++:
Python is a very good and elegant language. Without the troubles of semicolons and braces, you don't have to worry about braces matching and the trouble of skipping semicolons after the statement ends during development, this topic describes how to embed python into C ++ to bring your c ++ program to another level!
1. Install python,
2. First set the library file to include the include and lib in the python Directory into the library file and the library inclusion.
Now, let's start working. Let's look at a small program first:
- #include<python.h>#include<iostream>using
namespace std;int main(){ Py_Initialize(); /*
Initialize the python Interpreter
- */ PyRun_SimpleString("print 'hello world!'"); /*
Call the python statement */Py_Finalize ();/* to end the python interpreter, release the resource */}, and output hello world under the console program! This is our first program. The first and third lines are required. Let's look at more code, this is to call the functions in the python script in the c ++ program: First, write a script:
- ___def helloworld():
- _______print 'hello world!'
Save it as the first. py file to the directory of the current project. The Code is as follows:
- #include<python.h>int main(){PyObject* p_module
= NULL;PyObject* p_func = NULL;
Py_Initialize(); /*
Python interpreter Initialization
- */ p_module = PyImport_ImportModule("first");
p_func = PyObject_GetAttrString
(p_module, "hello");PyEval_CallObject
(p_func, NULL);Py_Finalize(); /*
End the Python interpreter and release the resource.
- */ return 0;}
- yImport_ImportModule()
Is the file to import the script, the parameter is the file name
- PyObject_GetAttrString()
Find the specified function PyEval_CallObject () from your import file. The NULL part is the function parameter. After running, you will see hello world! String.