Python export Function method __ function

Source: Internet
Author: User

1, Export function Example

#include <python/Python.h> #include <iostream> using namespace std;

int add (int arg1, int arg2) {return arg1 + arg2;}

int sub (int arg1, int arg2) {return arg1-arg2;}
	Static pyobject* Math_add (pyobject* self, pyobject* args) {int arg1, arg2; if (!
	Pyarg_parsetuple (args, "II", &arg1, &arg2)) {return NULL;
	int result = Add (arg1, arg2);
Return (pyobject*) py_buildvalue ("I", result);
	Static pyobject* Math_sub (pyobject* self, pyobject* args) {int arg1, arg2; if (!
	Pyarg_parsetuple (args, "II", &arg1, &arg2)) {return NULL;
	int result = SUB (arg1, arg2);
Return (pyobject*) py_buildvalue ("I", result); } static Pymethoddef mathmethods[] = {{"Add", Math_add, Meth_varargs, "Execute math Command:add."}, {"Sub", Math_su

B, Meth_varargs, "Execute math command:sub."}, {null, NULL}}; static struct Pymoduledef Mathmodule = {pymoduledef_head_init, "Math_capi", "example module Doc string",-1, Mathmet
	Hods, NULL, NULL, NULL,NULL};
Static pyobject* __matherror;
	Pymodinit_func Pyinit_math () {pyobject* module = pymodule_create (&mathmodule);
	if (null = = module) {return null;
	} __matherror = Pyerr_newexception ("Math.error", NULL, NULL);
	Py_incref (__matherror);
	Pymodule_addobject (module, "Error", __matherror);
return module;
	} std::string Format_python_traceback (Pyobject *tb) {pytracebackobject *trace = (pytracebackobject*) TB;

	std::string stack;
	stack = "traceback:\n";
		while (trace && trace->tb_frame) {/*pyframeobject *frame = (pyframeobject*) trace->tb_frame; Stack + + base::strfmt ("File \"%s\ ", line%i, in%s\n", pystring_asstring (frame->f_code->co_filename), trace-
		>tb_lineno, Pystring_asstring (frame->f_code->co_name));
		Pyobject *code = Pyerr_programtext (pystring_asstring (frame->f_code->co_filename), Trace->tb_lineno);
			if (code) {stack + = base::strfmt ("%s", Pystring_asstring (code));
		Py_decref (code); }*/trace = trace->tb_next;
} return stack;
	} std::string format_python_exception (std::string &summary) {std::string reason, stack;

	Pyobject *exc, *val, *TB;
	Pyerr_fetch (&exc, &val, &AMP;TB);

	Pyerr_normalizeexception (&exc, &val, &AMP;TB);
		if (val) {Pyobject *tmp = Pyobject_str (val);
			if (tmp) {reason = Pybytes_asstring (TMP);
		PY_DECREF (TMP);
	} if (tb) stack = Format_python_traceback (TB);

	else stack = "No stack information."

	Pyerr_restore (exc, Val, TB);

	Summary = reason;
return stack + reason+ "\ n";
	Static std::string Exception_detail () {Pyobject *exc_class = null, *EXC = NULL, *EXC_TB = NULL;
	Pyerr_fetch (&exc_class, &exc, &AMP;EXC_TB);
		if (exc) {Pyobject *str = pyobject_str (exc);
			if (str) {//char *s = pybytearray_asstring (str);

			Char *s = pybytes_asstring (str);
			if (s) return s;
		Py_decref (str);
	} py_decref (EXC);
	} py_xdecref (Exc_class);

	Py_xdecref (EXC_TB); Pyerr_restore (exc, VAL, TB);

Return "";}
	Call output "Hello world" function void HelloWorld () {Pyimport_appendinittab ("Math_capi", Pyinit_math);
	Py_initialize ();
	Pyimport_importmodule ("Math_capi");
	pyrun_simplestring ("Import sys");
	Pyrun_simplestring ("Sys.path.append ('. ')");
	Pyrun_simplestring ("Sys.path.append (';/')"); Pyrun_simplestring ("print ' Hello python! ')

	\ n ");
	pyobject* pmodule = Pyimport_importmodule ("Testpython");
	Pyerr_print ();
	std::string strerror = Exception_detail ();
	if (!pmodule) {return;
	} pyerr_print ();
	pyobject* Pfunc = pyobject_getattrstring (Pmodule, "HelloWorld");
	Pyerr_print ();
	if (Pfunc && Pycallable_check (pfunc)) {Pyobject_callobject (Pfunc, NULL);
} py_finalize ();
	//Call ADD function, pass two int parameter void Add () {py_initialize ();
	pyobject* pmodule = NULL;
	pyobject* pfunc = NULL;    Pmodule = Pyimport_importmodule ("Testpython");   Test:python filename Pfunc = pyobject_getattrstring (Pmodule, "add");        The function name//creation parameters in the Add:python file pyobject* PArgs = pytuple_new (2);         The parameter pass of function call is packaged in the form of tuple, 2 indicates the number of parameters Pytuple_setitem (PArgs, 0, Py_buildvalue ("I", 5)); 0---Ordinal i indicates the creation of an int variable pytuple_setitem (PArgs, 1, Py_buildvalue ("I", 7));
	1---Serial number//return value pyobject* Preturn = NULL;        Preturn = Pyeval_callobject (Pfunc, PArgs);
	Call function//convert return value to int type.
	int result;               Pyarg_parse (Preturn, "I", &result);
	I represents the conversion of the int variable cout << "5+7 =" << result << Endl; 
Py_finalize ();
	The type of the parameter pass is the dictionary void Testtransferdict () {py_initialize ();
	pyobject* pmodule = NULL;
	pyobject* pfunc = NULL;                      Pmodule = Pyimport_importmodule ("Testpython");                Test:python filename Pfunc = pyobject_getattrstring (Pmodule, "testdict"); 
	The function name//creation parameters in the Add:python file pyobject* PArgs = pytuple_new (1);                                     pyobject* pdict = Pydict_new ();   Create dictionary type variable pydict_setitemstring (pdict, "Name", Py_buildvalue ("s", "Scott")); Populate the dictionary type variable with data pydict_setitemstring (pdict, "Age", Py_buildvalue ("I"), 18));                                   Populate the dictionary type variable with data pytuple_setitem (PArgs, 0, pdict); 
	0---Ordinal adds a dictionary type variable to the parameter tuple//return value pyobject* Preturn = NULL;                          Preturn = Pyeval_callobject (Pfunc, PArgs);
	Call function//process return value int size = Pydict_size (Preturn);
	cout << "Returns the size of the dictionary as follows:" << size << Endl;
	Pyobject *pnewage = pydict_getitemstring (Preturn, "age");
	int newage;
	Pyarg_parse (Pnewage, "I", &newage);
	cout << "True Age:" << newage << Endl;
Py_finalize ();
	}//Test class void TestClass () {py_initialize ();
	pyobject* pmodule = NULL;
	pyobject* pfunc = NULL;                        Pmodule = Pyimport_importmodule ("Testpython");                  Test:python filename Pfunc = pyobject_getattrstring (Pmodule, "testdict");
	Add:python the function name in the file//Get person class pyobject* Pclassperson = Pyobject_getattrstring (pmodule, "person");
	Create an instance of the person class pyinstance_new pyobject* Pinstanceperson = Pyobject_callobject (pclassperson,null); //Call Method Pyobject_callmethod (Pinstanceperson, "greet", "s", "Hello Kitty");
s indicates that the string is passed, and the value is "Hello Kitty" py_finalize ();   

	the int main (int argc, char *argv[]) {/* pass argv[0] to the python interpreter * *//py_setprogramname (argv[0));
	cout << "Starting Test ..." << Endl;
	cout << "HelloWorld ()-------------" << Endl;
	HelloWorld ();
         cout << "Add ()--------------------" << Endl;
	ADD ();
	cout << "Testdict-----------------" << Endl;
	Testtransferdict ();
	cout << "TestClass----------------" << Endl;
	TestClass ();
	System ("pause");
return 0;   }


2, write the script

#testpython. py
Import Math_capi
Def HelloWorld ():
Print ("Hello world!")
Print (Math_capi.add (3,5))
Print (Math_capi.sub (5,3))
def add (A, B):
Return a+b
def testdict (dict):
Print (DICT)
Dict["Age" = 17
Return Dict
Class Person:
def greet (self, greetstr):
Print (GREETSTR)
#print Add (5,7)
#a = Raw_input ("Enter to Continue ...")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.