Next to the previous article import module (http://blog.csdn.net/xiadasong007/archive/2009/09/02/4512797.aspx), continue to analyze the basics of embedding. I will not talk about it this time. If you have any questions, please remember to check more English documents. I have little knowledge in this field in China.
Let's take a look at the code and I will go to bed after writing it ~
# Include "Python/python. H"
# Include <iostream>
Using namespace STD;
Int main (INT argc, char ** argv)
{
Pyobject * pmodule, * Pclass, * pstuobj, * pfunc;
Py_initialize ();
////////////////
// Load module Stu. py
Pmodule = pyimport_importmodule ("Stu ");
// Obtain the class student from the module
Pclass = pyobject_getattrstring (pmodule, "student ");
// Generate a student object Jack. Note that parentheses (s) must be added to version 3.1; otherwise, an error will occur.
// Pyobject_callobject is similar to another commonly used pyeval_callobject. For details, see the appendix.
Pyobject * temp = py_buildvalue ("(s)", "Jack ");
Pstuobj = pyobject_callobject (Pclass, temp );
// Obtain the member function printname in the function object Jack,
// This getattr means to get the attributes of the current object (not limited to attributes in C ++)
Pfunc = pyobject_getattrstring (pstuobj, "printname ");
// Call the printname Function
Pyeval_callobject (pfunc, null );
////////////////
Py_finalize ();
Return 0;
}
/*
Appendix:
1: Student class. I found that parentheses must be added after print. Otherwise, there will be problems.
Class student:
Name = ""
Def _ init _ (self, name ):
Self. Name = Name
Def printname (Self ):
Print (self. Name)
2: differences between pyobject_callobject and pyeval_callobject:
It can be seen that the latter is more direct and accepts null, and does explicit type checks
For ARGs and kwds.
Pyobject_callobject (pyobject * o, pyobject *)
{
! Pyobject * R;
! Pyobject * ARGs =;
!
! If (ARGs = NULL ){
! ARGs = pytuple_new (0 );
! If (ARGs = NULL)
! Return NULL;
! }
!
! R = pyeval_callobject (O, argS );
!
! If (ARGs! = ){
! Py_decref (ARGs );
! }
!
! Return R;
}
Pyobject_callobject (pyobject * o, pyobject *)
{
! Return pyeval_callobjectwithkeywords (O, A, null );
}
*/