473,241 Members | 1,528 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

How to create Python function in c++ & call it multiple times

I am new to Python. I would like to use Python for the specialized purpose of dynamic expressions parsing & evaluation in my C++ application.
I would like to encapsulate the expressions to be evaluated in Python function & compile that function at runtime, somewhat as below.
Expression to eval put in Python function
def isSizeSmall(size,vol,ADV,prod):
if ( (size < 1000) & (vol < (0.001 * ADV)) & (prod=="Stock")): print "OK"; return 10
else: print "NOK"; return 11

Then, I want to evaluate the PyObject returned by Py_CompileString multiple times in my program using the user input as the variables to the above function.
This I tried using two different approaches - 1) PyEval_evalCode, & 2) PyObject_CallObject.

1) When using PyEval_evalCode: The function call to PyEval_evalCode was ok, but it did not return any output.
2) Whereas, when I used this object with PyObject_CallObject, it failed with error as given below.

Any help will be great. Many thanks in advance for your help.
Warm Regards,
Ganesh

//***********************************************//
Output of my test program:
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"


str compiled fine with stdin & Py_file_input, calling PyEval_EvalCode
None ok [0] size [-1]

str compiled fine with stdin & Py_file_input, calling PyFunction_New & then PyObject_CallObject
Getting PyFunction_New
Calling PyObject_CallObject
func is callable
TypeError: ?() takes no arguments (4 given)

My test program having both above approaches is as below:
Expand|Select|Wrap|Line Numbers
  1. main(int argc, char **argv)
  2. {
  3.    /* Pass argv[0] to the Python interpreter */
  4.    Py_SetProgramName(argv[0]);
  5.    /* Initialize the Python interpreter.  Required. */
  6.    Py_Initialize();
  7.    PyRun_SimpleString("import sys\n");
  8.  
  9.    char szExpr[2048];
  10.    memset(szExpr,'\0',sizeof(szExpr));
  11.    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");
  12.  
  13.    printf("Expression to eval = \n[%s]\n",szExpr);
  14.  
  15.    OrderValues ordval;
  16.    ordval.size = 100;
  17.    ordval.ADV  = 100000;
  18.    ordval.vol  = 1000;
  19.    memset(ordval.prod,'\0',sizeof(ordval.prod));
  20.    sprintf(ordval.prod,"Stock");
  21.  
  22.  
  23.    PyObject *glb, *loc;
  24.  
  25.    glb = PyDict_New();
  26.    PyDict_SetItemString(glb, "__builtins__", PyEval_GetBuiltins());
  27.  
  28.    loc = PyDict_New();
  29.  
  30.    PyObject* tuple = PyTuple_New(4);
  31.    PyObject* val = 0;
  32.  
  33.    val = PyInt_FromLong(ordval.size);
  34.    PyTuple_SetItem(tuple,0,val);
  35.    PyDict_SetItemString(loc,"size",val);
  36.  
  37.    val = PyInt_FromLong(ordval.vol);
  38.    PyTuple_SetItem(tuple,1,val);
  39.    PyDict_SetItemString(loc,"vol",val);
  40.  
  41.    val = PyInt_FromLong(ordval.ADV);
  42.    PyTuple_SetItem(tuple,2,val);
  43.    PyDict_SetItemString(loc,"ADV",val);
  44.  
  45.    val = PyString_FromString(ordval.prod);
  46.    PyTuple_SetItem(tuple,3,val);
  47.    PyDict_SetItemString(loc,"prod",val);
  48.  
  49.  
  50. /*** with string & Py_file_input ***/
  51.    PyObject* result = NULL;
  52.    result = Py_CompileString(szExpr,"<string>", Py_file_input);
  53.    if(result!=NULL && !PyErr_Occurred()){
  54.      printf("str compiled fine with stdin & Py_file_input, calling PyEval_EvalCode\n");
  55.  
  56.      PyCodeObject *pyCo = (PyCodeObject *)result;
  57.      PyObject* evalret = NULL;
  58.      evalret = PyEval_EvalCode(pyCo,glb,loc);
  59.      if(!evalret || PyErr_Occurred())
  60.        PyErr_Print();
  61.      else
  62.         printf("ok [%d] size [%d]\n",PyObject_Print(evalret,stdout,0),PyObject_Size(evalret));
  63.  
  64.      // Try to get function obj of this...
  65.      printf("Getting PyFunction_New\n");
  66.      PyObject* func = PyFunction_New(result,glb);
  67.      if(!func || PyErr_Occurred()){
  68.        printf("Failed to get Function..\n");
  69.        PyErr_Print();
  70.      } else {
  71.          printf("Calling PyObject_CallObject\n");
  72.          if(PyCallable_Check(func))
  73.            printf("func is callable\n");
  74.          PyObject* ret = PyObject_CallObject(func, tuple);
  75.          //PyObject* ret = PyObject_CallObject(func, NULL);
  76.          if(!ret || PyErr_Occurred())
  77.            PyErr_Print();
  78.          else
  79.            printf("PyObject_CallObject evaluated..\n");
  80.      }
  81.    } else {
  82.          printf("Py_CompileString-1 returned NULL\n");
  83.          PyErr_Print();
  84.    }
  85.    exit(100);
  86. }
Nov 21 '07 #1
0 2261

Sign in to post your reply or Sign up for a free account.

Similar topics

467
by: mike420 | last post by:
THE GOOD: 1. pickle 2. simplicity and uniformity 3. big library (bigger would be even better) THE BAD:
10
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. ...
25
by: Russell | last post by:
I want my code to be Python 3000 compliant, and hear that lambda is being eliminated. The problem is that I want to partially bind an existing function with a value "foo" that isn't known until...
29
by: Gerald | last post by:
Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my curriculum did not include Python programming yet I see many vacancies for Python developers.I studied programming Pascal,C++ and...
20
by: Mr.SpOOn | last post by:
Hi, I need a structure to represent a set of integers. I also need to perform on this set some basic set operations, such as adding or removing elements, joining with other sets and checking for...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.