关于嵌入python的问题
Programming Python, 2nd Edition上的例子
usermod.py 文件
import string
message = 'The meaning of life...'
def transform(input):
input = string.replace(input, 'life', 'Python')
return string.upper(input)
embed-object.c
#include <Python.h>
main( ) {
char *cstr;
PyObject *pstr, *pmod, *pfunc, *pargs;
printf("embed-object\n");
Py_Initialize( );
/* get usermod.message */
pmod = PyImport_ImportModule("usermod");
pstr = PyObject_GetAttrString(pmod, "message");
/* convert string to C */
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);
Py_DECREF(pstr);
/* call usermod.transform(usermod.message) */
pfunc = PyObject_GetAttrString(pmod, "transform");
pargs = Py_BuildValue("(s)", cstr);
pstr = PyEval_CallObject(pfunc, pargs);
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);
/* free owned objects */
Py_DECREF(pmod);
Py_DECREF(pstr);
Py_DECREF(pfunc); /* not really needed in main( ) */
Py_DECREF(pargs); /* since all memory goes away */
}
不知为什么PyImport_ImportModule总返回为NULL,但如果PyImport_ImportModule("math")就能成功。
问题点数:100、回复次数:4Top
1 楼xyzxyz1111(程序员的自我修养)回复于 2004-12-01 21:59:42 得分 100
usermod.py 和可执行文件的路径个是什么?Top
2 楼wjh1014(wjh)回复于 2004-12-02 10:49:18 得分 0
都放在同一个文件夹下面,并且执行 pmod = PyImport_ImportModule("usermod");时生成了usermod.pyc文件,但pmod为NULL啊Top
3 楼xyzxyz1111(程序员的自我修养)回复于 2004-12-02 14:19:53 得分 0
我运行了一遍,发现并没有成为NULL,一切正常牙。
你用的是Debug还是Release?我用的是Release
python 2.3.3
VC 6.0
编意完后把Release目录下的可执行文件放到usermod同目下,然后执行第。
Top
4 楼wjh1014(wjh)回复于 2004-12-08 17:27:48 得分 0
多谢xyzxyz1111(如是我闻)
我重新装了个python2。4,可以了
Top




