int newAge;
PyArg_Parse(pNewAge, "i", &newAge);
cout << "True Age: " << newAge << endl;
Py_Finalize();
}
void TestClass()
{
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");
PyObject *pClassPerson = PyObject_GetAttrString(pModule, "Person");
PyObject *pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL);
PyObject_CallMethod(pInstancePerson, "greet", "s", "Hello Kitty");
Py_Finalize();
}
Test001.py
[python]
def HelloWorld():
print "Hello World"
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...")
def HelloWorld():
print "Hello World"
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...")
3、
其中
[cpp]
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
分别导入sys,接着设置py文件的路径
4、PySys_SetArgv、PySys_SetPath和PyRun_AnyFile的用法:
test1.c
[cpp]
#include "Python.h"
void HelloWorld(){
char *argv[2];
unsigned int argc;
argc = 2;
char *tmp="hello";
char *tmp1="world";
argv[0]= tmp;
argv[1]= tmp1;
Py_Initialize();
PySys_SetArgv(argc, argv);
PySys_SetPath("./");
// PyRun_SimpleString("import sys");
// PyRun_SimpleString("sys.path.append('./')");
PyRun_SimpleString("print 'hi,python!'");
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule("mypy");
Py_Finalize();
}
void main(){
printf("tttttt\n");
HelloWorld();
}
#include "Python.h"
void HelloWorld(){
char *argv[2];
unsigned int argc;
argc = 2;
char *tmp="hello";
char *tmp1="world";
argv[0]= tmp;
argv[1]= tmp1;
Py_Initialize();
PySys_SetArgv(argc, argv);
PySys_SetPath("./");
// PyRun_SimpleString("import sys");
// PyRun_SimpleString("sys.path.append('./')");
PyRun_SimpleString("print 'hi,python!'");
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule("mypy");
Py_Finalize();
}
void main(){
printf("tttttt\n");
HelloWorld();
}
mypy.py
[python]
#!/usr/bin/env python
import sys
print '----sys.argv[0]: ',sys.argv[0]
print '----sys.argv[1]: ',sys.argv[1]
print '2222'
def HelloWorld():
print 'this is Helloworld'
if __name__ == '__main__':
print 'this is main
#!/usr/bin/env python
import sys
print '----sys.argv[0]: ',sys.argv[0]
print '----sys.argv[1]: ',sys.argv[1]
print '2222'
def HelloWorld():
pr