[ Please help ] how to create Python functions in C++ at runtime & call them
grbgooglefan
ganeshborse at gmail.com
Wed Nov 21 02:32:09 EST 2007
I want to compile following type of python function in my C++ program
at runtime.
def isSizeSmall(size,vol,ADV,prod):
if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod=="Stock")):
print "OK"; return 10
else: print "NOK"; return 11
Using Py_CompileString, I compiled a code object from this function,
like:
char szExpr[2048];
sprintf(szExpr,"def isSizeSmall(size,vol,ADV,prod):\n if ( (size <
1000) & (vol < (0.001 * ADV)) & (prod==\"Stock\")): print \"OK\";
return 10\n else: print \"NOK\"; return 11\n\n\n");
PyObject* result = Py_CompileString(szExpr,"<string>",
Py_file_input);
Then, I tried to call this function in 3 different ways: 1)
PyEval_EvalCode, 2) PyObject_CallObject.
But both failed.
For using PyObject_CallObject, I did something like this.
PyObject* tuple = PyTuple_New(4);
PyObject* val = 0;
val = PyInt_FromLong(ordval.size);
PyTuple_SetItem(tuple,0,val);
val = PyInt_FromLong(ordval.vol);
PyTuple_SetItem(tuple,1,val);
val = PyInt_FromLong(ordval.ADV);
PyTuple_SetItem(tuple,2,val);
val = PyString_FromString(ordval.prod);
PyTuple_SetItem(tuple,3,val);
PyObject *glb = PyDict_New();
PyDict_SetItemString(glb, "__builtins__", PyEval_GetBuiltins());
PyObject* func = PyFunction_New(result,glb);
if(!func || PyErr_Occurred()){
printf("Failed to get Function..\n");
PyErr_Print();
} else {
printf("Calling PyObject_CallObject\n");
if(PyCallable_Check(func))
printf("func is callable\n");
PyObject* ret = PyObject_CallObject(func, tuple);
if(!ret || PyErr_Occurred())
PyErr_Print();
else
printf("PyObject_CallObject evaluated..\n");
}
I got this output. Why is it so? Why is this function not taking any
parameters? Please help.
Expression to eval =
[def isSizeSmall(size,vol,ADV,prod):
if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod=="Stock")): print
"OK"; return 10
else: print "NOK"; return 11
]
func is callable
TypeError: ?() takes no arguments (4 given)
Thanks for all help & guidance
More information about the Python-list
mailing list