| The code is as follows: |
Copy code |
|
# Include <python2.7/Python. h>
Int main (){
PyObject * g_pModule = NULL;
Py_Initialize (); // before using python, you need to call Py_Initialize (); this function is initialized.
If (! Py_IsInitialized ())
{
Printf ("init errorn ");
Return-1;
}
PyRun_SimpleString ("import sys ");
PyRun_SimpleString ("sys. path. append ('./')");
G_pModule = PyImport_ImportModule ("test"); // The name of the file to be called. Here we are test. py in the current directory.
If (! G_pModule ){
Printf ("Cant open python file! N ");
Return-2;
}
PyObject * test1 = PyObject_GetAttrString (g_pModule, "test1"); // The name of the function to be called.
PyObject * objResult = PyObject_CallFunction (test1, "I, s", 2, e); // call a function
If (! ObjResult ){
Printf ("invoke function failn ");
}
PyObject * test2 = PyObject_GetAttrString (g_pModule, "test2"); // The name of the function to be called.
ObjResult = PyObject_CallFunction (test2, "I", 2); // call a function
Char * x = PyString_AsString (objResult );
Printf ("% sn", x );
Py_Finalize (); // call Py_Finalize, which corresponds to Py_Initialize.
} |
Python program test. py
| The code is as follows: |
Copy code |
|
Def test1 (s, str ):
Print s + str
Return 0
Def test2 (s ):
Return s |
C program compilation method
| The code is as follows: |
Copy code |
|
# If We install python in/opt/python during compilation, we can use this command to compile the program.
$ Gcc-I/opt/python/include-L/opt/python/lib/-lpython2.7 test. c |
Note: To compile python, you must add the -- enable-shared library to the dynamic link library.
| The code is as follows: |
Copy code |
|
./Configure -- prefix =/opt/python -- enable-shared |