1、例程:
test.c
[cpp]
#include "Python.h"
void HelloWorld(){
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("print 'hi,python!'");
PyRun_SimpleString("sys.path.append('./')");
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
printf("11111 %x\n",pModule);
pModule =PyImport_ImportModule("mypy");
printf("11111 %x\n",pModule);
pFunc= PyObject_GetAttrString(pModule, "HelloWorld");
Pyeva l_CallObject(pFunc, NULL);
Py_Finalize();
}
void main(){
printf("tttttt\n");
HelloWorld();
}
#include "Python.h"
void HelloWorld(){
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("print 'hi,python!'");
PyRun_SimpleString("sys.path.append('./')");
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
printf("11111 %x\n",pModule);
pModule =PyImport_ImportModule("mypy");
printf("11111 %x\n",pModule);
pFunc= PyObject_GetAttrString(pModule, "HelloWorld");
Pyeva l_CallObject(pFunc, NULL);
Py_Finalize();
}
void main(){
printf("tttttt\n");
HelloWorld();
}
mypy.py
[python]
#!/usr/bin/env python
print '2222'
def HelloWorld():
print 'this is Helloworld'
#!/usr/bin/env python
print '2222'
def HelloWorld():
print 'this is Helloworld'
编译: mips-linux-gnu-gcc -EL test.c -L./lib -lpython2.7 -I./include/python2.7/
2、例程:
test.cpp
[cpp]
#include
#include "Python.h"
using namespace std;
void HelloWorld();
void Add();
void TestTransferDict();
void TestClass();
int main()
{
cout << "Starting Test..." << endl;
cout << "HelloWorld()-------------" << endl;
HelloWorld();
cout << "Add()--------------------" << endl;
Add();
cout << "TestDict-----------------" << endl;
TestTransferDict();
cout << "TestClass----------------" << endl;
TestClass();
// system("pause");
return 0;
}
void HelloWorld()
{
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("print 'hi,python!'");
PyRun_SimpleString("sys.path.append('./')");
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule("Test001");
pFunc= PyObject_GetAttrString(pModule, "HelloWorld");
Pyeva l_CallObject(pFunc, NULL);
Py_Finalize();
}
void Add()
{
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule("Test001");
pFunc= PyObject_GetAttrString(pModule,"add");
PyObject *pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 5));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 7));
PyObject *pReturn = NULL;
pReturn = Pyeva l_CallObject(pFunc, pArgs);
int result;
PyArg_Parse(pReturn, "i", &result);
cout << "5+7 = " << result << endl;
Py_Finalize();
}
void TestTransferDict()
{
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule("Test001");
pFunc= PyObject_GetAttrString(pModule, "TestDict