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;
}

1 件のコメント:

ignitz さんのコメント...

hi, you're programmer too... When I will enter the university the we can share knowledge and ideas.

I'm from brazil and my hobby is tranlate games to portguese...
http://www.niitsuma.co.cc/Final%20Fantasy%20VII%20Screenshots/024.jpg

I make tools in C/C++ sample and I'm studying to University and the all projects are stoped, when I enter will restart again with programmer.

Sorry for my english.
Me Niitsuma too.