moved to http://www2s.biglobe.ne.jp/~niitsuma/pyjsonrpcembd.html
in Japanse http://d.hatena.ne.jp/niitsuma/20080209/1233260146
2009年1月30日金曜日
2009年1月29日木曜日
python embedding simple example
http://docs.python.org/extending/embedding.html
In some environment, this example fail to import python file multiple.py .
The following provides another example of assessing to python function's result and augments from C.
--------------------------
#include
int main()
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
Py_Initialize();
//def myfun
PyRun_SimpleString(
"def myfun(a):\n"
"\tprint a\n"
"\treturn a*a\n"
);
//extract interface to myfun
pName = PyString_FromString( "__main__");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
pFunc = PyObject_GetAttrString(pModule, "myfun");
pArgs = PyTuple_New(1);
pValue = PyInt_FromLong(atoi("3"));
PyTuple_SetItem(pArgs, 0, pValue);
//execute myfun
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
//get result
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
//simple do
PyRun_SimpleString("print myfun(3)\n");
//finalize
Py_DECREF(pModule);
Py_Finalize();
return 0;
}
In some environment, this example fail to import python file multiple.py .
The following provides another example of assessing to python function's result and augments from C.
--------------------------
#include
int main()
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
Py_Initialize();
//def myfun
PyRun_SimpleString(
"def myfun(a):\n"
"\tprint a\n"
"\treturn a*a\n"
);
//extract interface to myfun
pName = PyString_FromString( "__main__");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
pFunc = PyObject_GetAttrString(pModule, "myfun");
pArgs = PyTuple_New(1);
pValue = PyInt_FromLong(atoi("3"));
PyTuple_SetItem(pArgs, 0, pValue);
//execute myfun
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
//get result
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
//simple do
PyRun_SimpleString("print myfun(3)\n");
//finalize
Py_DECREF(pModule);
Py_Finalize();
return 0;
}
登録:
投稿 (Atom)