I learned it using vc2003 + python2.5, and the other ones should not be much different.
0. Bad Environment Settings
Add the include/libs directory of python to include/lib directories of VC respectively. In addition, Python does not provide debug Lib. Specifically, Python does not provide python25_d.lib. You can compile Python source code to obtain python25_d.lib. I have not tried it yet. And I did not download it after I found it online. Therefore, if you want to run the program in debug, you need to set pyconfig. H (in the python25/include/directory) is probably in the 283 line, change Pragma comment (Lib, "python25_d.lib") to Pragma comment (Lib, "python25.lib "), make Python use non-Debug Lib.
1. Programming started.
# Include <python. h>
The first step is to include the python header file.
2. Let's look at a simple example.
1) the python file test. py defines a function very easily.
# Filename test. py
Def Hello ():
Print "Hello, world! "
Should this be understandable? Otherwise, go back and practice python. Simple Python tutorial, by swaroop, C. H. Translated by Shen jieyuan.
2) CPP File
# Include <python. h> // contains the header file. It is required to embed python in C ++.
Int main ()
{
Py_initialize ();
Pyobject * pmodule = NULL;
Pyobject * pfunc = NULL;
Pmodule = pyimport_importmodule ("test ");
Pfunc = pyobject_getattrstring (pmodule, "hello ");
Pyeval_callobject (pfunc, null );
Py_finalize ();
Return 0;
}
The first step is to include the header file.
Step 2: Before using python, call py_initialize (); to initialize the function.
For example:
The basic initialization function is py_initialize (). this initializes the table of loaded modules, and creates the fundamental modules _ builtin __, _ main __, sys, and exceptions. it also initializes the module search path (sys. path ).
You must call it at the beginning.
Step 3: declare Python variables of the pyobject type. In fact, the statement can also be put in front of it. It doesn't matter.
Step 4: import module, that is, your script name. You do not need to add a suffix. Otherwise, errors will occur.
Step 5: Obtain the function from the module you import.
Pfunc = pyobject_getattrstring (pmodule, "hello ");
The above example is clear enough. The last one is the name of the function you want to obtain.
Step 6: Call pyeval_callobject to execute your function. The second parameter is the function of the function to be called. This example does not contain parameters, so it is set to null.
Step 7: Call py_finalize, which corresponds to py_initialize. One is at the beginning and the other is at the end.
Write the tutorial for the first time. This example is very simple, and I am still studying it as an Arab Emirates. I can only ensure that you can run this example. We suggest you go to Python's pluentaion, which describes how to use embedding python. I wrote it here, but I only learned so much now. After learning more, write it again. Over. Well