#include //python33(python2.x有几个函数不对应)/*PyImport_ImportModule
导入一个Python模块并返回它的指针
PyModule_GetDict
获取一个模块的属性字典对象
PyRun_String
在指定的名字空间内运行代码串
PyObject_SetAttrString
通过namestring为一个对象的属性赋值
PyArg_Parse
将Python返回值对象转换为C语言形式
PyObject_GetAttrString
按名字获取对象的属性值
PyEval_CallObject
调用Python的函数(或类,或方法)
PyArg_Parse
将Python对象转换为C语言值
Py_BuildValue
将C语言值转换为Python对象
PyDict_New
构造一个新的空字典对象
PyDict_SetItemString
给一个字典的键值赋值
PyDict_GetItemString
按键值获取(查询)一个字典值
PyEval_GetBuiltins
得到内置作用域的模块*/
/*******usermod.py********
message = 'The meaning of life...'
def transform(input):
input = input.replace('life', 'Python')
return input.upper()*/
intmain() {int *cval, i;char *cstr;
PyObject*pstr, *pmod, *pdict, *pfunc, *pargs, *pval;
Py_Initialize();
pmod= PyImport_ImportModule("usermod");
pdict=PyModule_GetDict(pmod);
pstr= PyRun_String("message", Py_eval_input, pdict, pdict);
PyArg_Parse(pstr,"s", &cstr);
printf("%s\n", cstr);
PyObject_SetAttrString(pmod,"X", pstr);
(void) PyRun_String("print(transform(X))", Py_file_input, pdict, pdict);
pstr= PyObject_GetAttrString(pmod, "message");
PyArg_Parse(pstr,"s", &cstr);
printf("%s\n", cstr);
Py_DECREF(pstr);
pfunc= PyObject_GetAttrString(pmod, "transform");
pargs= Py_BuildValue("(s)", cstr);
pstr=PyEval_CallObject(pfunc, pargs);
PyArg_Parse(pstr,"s", &cstr);
printf("%s\n", cstr);
pdict=PyDict_New();
PyDict_SetItemString(pdict,"__builtins__", PyEval_GetBuiltins( ));
PyDict_SetItemString(pdict,"Y", Py_BuildValue("l", 2));
PyRun_String("X = 99", Py_file_input, pdict, pdict);
PyRun_String("X = X+Y", Py_file_input, pdict, pdict);
pval= PyDict_GetItemString(pdict, "X");
PyArg_Parse(pval,"i", &cval);
printf("%d\n", cval);
Py_DECREF(pdict);
Py_DECREF(pmod);
Py_DECREF(pstr);
Py_DECREF(pfunc);
Py_DECREF(pargs);
Py_Finalize();return 0;
}