473,657 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

4 New Member
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(siz e,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_CompileStrin g 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_CallOb ject.

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_CallOb ject, 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(siz e,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_CallOb ject
Getting PyFunction_New
Calling PyObject_CallOb ject
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 2307

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

Similar topics

467
21457
by: mike420 | last post by:
THE GOOD: 1. pickle 2. simplicity and uniformity 3. big library (bigger would be even better) THE BAD:
10
3681
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. Andrew dalke@dalkescientific.com
25
2556
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 run-time: someobject.newfunc = lambda x: f(foo, x) The reason a nested function doesn't work for this is that it is, well, dynamic. I don't know how many times or with what foo's this will be done.
29
560
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 Delphi.So I need to catch up quickly and master Python programming.How do you suggest that I achieve this goal?Is python platform independent?What is the best way?And how long would it take before I can develop applications using python?Can you...
20
2440
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 the presence of specific elements. I think that using Python sets would be the best choice, but I also need integers to be ordered inside the set and I've just found out that, instead, Python sets are unordered collections.
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8730
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7321
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1607
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.