C + + calls Python

Source: Internet
Author: User

Recently learning Python, mainly learning scripting language, can be cross-platform, lightweight, and have the tools to do some testing. And of course because, when you look at boost books, it says C + + can call Python, so it took a while to learn. Now start learning C + + calling Python.

After you install Python, there are header files in the installation directory, and Libs,vs can refer to Python by setting both.


Project settings are simple, the main project header file directory is set to include, and the library directory is set to libs.

You only need to refer to the "Python.h" header file when you use it.

Note: Under 1.debug, Python27.lib needs to replicate a copy named Python27_d.lib

 CallPython.cpp :  defines the entry point of the console application. #include   "stdafx.h" #include   "Python.h" #include  <iostream>using namespace std; Void testcallfunc (); Void testcallfuncdict (); Void testclass (); Int _tmain (INT&NBSP;ARGC,  _tchar* argv[]) {testcallfunc (); Testcallfuncdict (); TestClass (); GetChar (); return 0;} Void testcallfunc () {py_initialize ();//  before using Python, to invoke Py_initialize initialization pyobject* pmodule =  NULL; pyobject* pfunc = null; Pyobject* paddfunc = null;pmodule = pyimport_importmodule ("TestPython");//  load module, Load py file if  (pmodule) {//  load function, HelloWorld, no parameter pfunc = pyobject_getattrstring (pmodule,  " HelloWorld ");//  gets the function of the module if  (pFunc) {pyeval_callobject (pfunc, null);//  call function, NULL indicates NULL parameter//PY_ Decref (PFunc);} else{cout <<  "Pfunc = null" &NBSP;&LT;&LT;&NBSP;ENDL;}   Load function, add, two parameters Paddfunc = pyobject_getattrstrING (pmodule,  "add");if  (paddfunc) {//  create parameter pyobject* pargs = pytuple_new (2);// The parameter passing of the   function call is pytuple_setitem in the form of tuples (Pargs, 0, py_buildvalue ("I",  5);// 0 --  Ordinal, I means to create an int variable pytuple_setitem (pargs, 1, py_buildvalue ("I",  7));// 1 --  ordinal//   return value Pyobject* preturn = null;//preturn = pyeval_callobject (PAddFunc, pArgs) ;//  Incoming multiple parameters//preturn = pyeval_callfunction (paddfunc,  "II",  5, 7);p return =  pyobject_callfunction (paddfunc,  "II", &NBSP;5,&NBSP;7);//  return value to int type int result; Pyarg_parse (preturn,  "i",  &result);cout <<  "5 + 7 = "   << result << endl;//py_decref (Paddfunc);} else{cout <<  "Paddfunc = null"  << endl;}} else{cout <<  "Pmodule = null" &NBSP;&LT;&LT;&NBSP;ENDL;} Py_decref (Pmodule); Py_finalize ();//  release}void testcallfuncdict () {py_initialize (); pyobject* pmodule = null; Pyobject* pfunc = null;pmodule = pyimport_importmodule ("TestPython");if  (PModule {pfunc = pyobject_getattrstring (pmodule,  "Testdict");if  (pFunc) {//  set parameter dictionary pyobject*  pargs = pytuple_new (1); Pyobject* pdict = pydict_new (); Pydict_setitemstring (pdict,  "Name",  py_buildvalue ("s",  "Longma")); Pydict_setitemstring (pdict,  "Age",  py_buildvalue ("I",  25)); Pytuple_setitem (pargs, 0, pdict); Pyobject* preturn = pyeval_callobject (Pfunc, pargs);//  processing return value int size =  pydict_size (Preturn);cout <<  "The size of the returned dictionary is:"  << size << endl ; Pyobject* pnewage = pydict_getitemstring (preturn,  "age"); int newage = _ Pyint_asint (Pnewage);//pyarg_parse (pnewage,  "i",  &neWage);cout <<  "true age: "  << newAge << endl; Pyobject* pnewname = pydict_getitemstring (preturn,  "Name");char* pname =  Pystring_asstring (pnewname);cout <<  "true name: "  << pName < < endl;//py_decref (PFunc);}} Py_finalize ();} Void testclass () {py_initialize (); Pyobject* pmodule = null;pmodule = pyimport_importmodule ("TestPython");if  ( Pmodule) {//  Gets the person class pyobject* pclassperson = pyobject_getattrstring (pModule,  "person ");//  create a Person class instance pyobject* pinstanceperson = pyinstance_new (pclassperson, null,  NULL);//  Call method Greet method Pyobject_callmethod (pinstanceperson,  "greet",  "s",  "Hello kitty") ;//  Incoming multiple parameters//pyobject_callmethod (pinstanceperson,  "greet",  "si",  "Hello kitty",  10);} Py_finalize ();}


Python code

testpython.py

Def HelloWorld (): Print "Hello World" def add (A, B): Return a+b def testdict (dict): Print Dict dict[ "Age"] = dict["Name"] = "Royma" Return Dict class Person:def greet (self, greetstr): Print greetst R


C + + calls Python

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.