C calls Python

Source: Internet
Author: User

 

CMediumCallPython

# Include <Python. H>

Int main (INT argc, char * argv [])

{

Py_initialize ();

Pyrun_simplestring ("From time import time, ctime/N"

"Print 'Today is ', ctime (Time ()/n ");

Py_finalize ();

Return 0;

}

 

 

 

 

 

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.

 

 

 

 

 

 

The Code is as follows, which demonstrates the direct execution of Python statements, no return of non-parameter function calls, and the return of Single-Parameter Function calls. Return multi-parameter function call:

# Include <python. h>
# Include <iostream>
Using namespace STD;

// Execute the python command
Void execpythoncommand ()
{
// Directly execute
Pyrun_simplestring ("From time import time, ctime/N"
"Print 'Today is ', ctime (Time ()/n ");
}

// Call a function without Parameters
Void invokenoparm ()
{
Pyobject * pmod = NULL;
Pyobject * pfunc = NULL;
// Import module
Pmod = pyimport_importmodule ("life ");
If (pmod)
{
// Obtain the function address
Pfunc = pyobject_getattrstring (pmod, "");
If (pfunc)
{
// Function call
Pyeval_callobject (pfunc, null );
}
Else
{
Cout <"cannot find function a" <Endl;
}
}
Else
{
Cout <"cannot find life. py" <Endl;
}
}

// Call a Parameter Function
Void invokewith1parm ()
{
Pyobject * pmod = NULL;
Pyobject * pfunc = NULL;
Pyobject * pparm = NULL;
Pyobject * pretval = NULL;
Int iretval = 0;
// Import module
Pmod = pyimport_importmodule ("funcdef ");
If (pmod)
{
Pfunc = pyobject_getattrstring (pmod, "square ");
If (pfunc)
{
// Create parameters
Pparm = py_buildvalue ("(I)", 5 );
// Function call
Pretval = pyeval_callobject (pfunc, pparm );
// Parse the return value
Pyarg_parse (pretval, "I", & iretval );
Cout <"square 5 is:" <iretval <Endl;
}
Else
{
Cout <"cannot find Function Square" <Endl;
}
}
Else
{
Cout <"cannot find funcdef. py" <Endl;
}
}

// Call a multi-parameter Function
Void invokewith2parm ()
{
Pyobject * pmod = NULL;
Pyobject * pfunc = NULL;
Pyobject * pparm = NULL;
Pyobject * pretval = NULL;
Int iretval = 0;
// Import module
Pmod = pyimport_importmodule ("add ");
If (pmod)
{
Pfunc = pyobject_getattrstring (pmod, "add ");
If (pfunc)
{
// Create two parameters
Pparm = pytuple_new (2 );
// Assign values to parameters
Pytuple_setitem (pparm, 0, py_buildvalue ("I", 2000 ));
Pytuple_setitem (pparm, 1, py_buildvalue ("I", 3000 ));
// Function call
Pretval = pyeval_callobject (pfunc, pparm );
// Parse the return value
Pyarg_parse (pretval, "I", & iretval );
Cout <"2000 + 3000 =" <iretval <Endl;
}
Else
{
Cout <"cannot find Function Square" <Endl;
}
}
Else
{
Cout <"cannot find Add. py" <Endl;
}
}

Int main (INT argc, char * argv [])
{
Py_initialize (); // Python interpreter Initialization

Execpythoncommand ();
Invokenoparm ();
Invokewith1parm ();
Invokewith2parm ();

Py_finalize (); // garbage collection, clear import/export warehouse
Return 0;
}

Related Article

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.