| | |
calling Python function from C/C++
Thread Solved |
•
•
Join Date: Aug 2005
Posts: 148
Reputation:
Solved Threads: 6
Hello,
I'm writing a simple calculator in C. The main problem is I need to parse string to evaluate for example 1+2*(3-1)/2.5.
However writing such parses is a very hard task.
This is a trivial thing Python using this code:
I saw that Python has C API so I assume that Python functions can be called from C.
Is it possible to use Python function eval() to evaluate user string in C program? In other words is it possible to make wrapper to this Python code and evaluate expression in C?
I tried to find answer in Python manual but I'm a complete jackass beginer.
For example I have Test.c
and from that c file I'd like to call eval and if success to store result to variable res.
I'm using MSCV++ .NET with Win XP and I assume I'll need to use some kind of Python libraray...
There is explanation in Pythion doc, but there is no complete testing source file and my english is not very good to understand all the described steps.
Is this possible at all?
Please, can you help me?
Thanks in advance!
I'm writing a simple calculator in C. The main problem is I need to parse string to evaluate for example 1+2*(3-1)/2.5.
However writing such parses is a very hard task.
This is a trivial thing Python using this code:
Python Syntax (Toggle Plain Text)
s = raw_input('Please enter expression:') try: x = eval(s) except NameError: print 'Unknown elements in the expression!' except ZeroDivisionError: print 'Division with zero attempted!' except: print 'Some other kind of error!' else: print 'Expression is evaluated correctly'
I saw that Python has C API so I assume that Python functions can be called from C.
Is it possible to use Python function eval() to evaluate user string in C program? In other words is it possible to make wrapper to this Python code and evaluate expression in C?
I tried to find answer in Python manual but I'm a complete jackass beginer.
For example I have Test.c
Python Syntax (Toggle Plain Text)
#include <stdio.h> char buff[BUFSIZ]; int main(void) { char * p; double res;/* to store result of expression evaluation*/ printf ("Please enter expression: "); fgets(buff, sizeof buff, stdin); if (p = strrchr(buff,'\n')) { *p = '\0'; } /* now wrapper to python function eval()-....? */ }
and from that c file I'd like to call eval and if success to store result to variable res.
I'm using MSCV++ .NET with Win XP and I assume I'll need to use some kind of Python libraray...
There is explanation in Pythion doc, but there is no complete testing source file and my english is not very good to understand all the described steps.
Is this possible at all?
Please, can you help me?
Thanks in advance!
•
•
Join Date: Aug 2005
Posts: 148
Reputation:
Solved Threads: 6
well I manage to figure it out myself. I'm using Bloodshed Dev-cpp
Here's the code:
I need to add include and lib directories to the project in order to everything works fine. Also Test.py is copied in Dev-cpp source code's folder.
Test file contains the following code
However there is an error. Look at the line stringarg = PyString_FromString("5"); If I put this:
stringarg = PyString_FromString("5+2"); or even this stringarg = PyString_FromString("5.0");
Program crashes at line Py_Finalize(). Program tries to read some memory location and suffer run time exception.
Only suggestion is to try to send it to Microsoft.
Why is this happening?
Everything (seems to) works fine I comment line Py_Finalize(), but I know that this is not a real solution.
Does anybode have a clue what is happening?
Thanks
Here's the code:
Python Syntax (Toggle Plain Text)
#include "python.h" #include <stdio.h> int main(int argc, char* argv[]) { double answer = 0; PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt; Py_Initialize(); modname = PyString_FromString("Test"); mod = PyImport_Import(modname); if (mod) { mdict = PyModule_GetDict(mod); func = PyDict_GetItemString(mdict, "doit"); /* borrowed reference */ if (func) { if (PyCallable_Check(func)) { stringarg = PyString_FromString("5");/*pay attention here*/ args = PyTuple_New(1); PyTuple_SetItem(args, 0, stringarg); rslt = PyObject_CallObject(func, args); if (rslt) { answer = PyFloat_AsDouble(rslt); Py_XDECREF(rslt); } Py_XDECREF(stringarg); Py_XDECREF(args); } } Py_XDECREF(mod); } Py_XDECREF(modname); Py_Finalize(); printf("%g",answer); return 0; }
Test file contains the following code
Python Syntax (Toggle Plain Text)
def doit(x1): try: x2 = eval(x1) except: print 'Error!' return 0 else: return x2
However there is an error. Look at the line stringarg = PyString_FromString("5"); If I put this:
stringarg = PyString_FromString("5+2"); or even this stringarg = PyString_FromString("5.0");
Program crashes at line Py_Finalize(). Program tries to read some memory location and suffer run time exception.
Only suggestion is to try to send it to Microsoft.
Why is this happening?
Everything (seems to) works fine I comment line Py_Finalize(), but I know that this is not a real solution.
Does anybode have a clue what is happening?
Thanks
•
•
Join Date: Aug 2005
Posts: 148
Reputation:
Solved Threads: 6
•
•
•
•
Originally Posted by vegaseat
A little twist here, the Python24.dll contains all the PyEval routines and they are most likely written in C. So I wonder, if you couldn't access them directly from the dll in your C/C++ program.
And also, can you help me to figure out why I'm getting that nasty send to Microsoft window and why my program read memory which is not supposed to?
Thank you
It looks like Boost.Python might be what you are looking for, check out this site:
http://www.boost.org/libs/python/doc/
http://www.boost.org/libs/python/doc/
May 'the Google' be with you!
If you have Dev-C++, embedding Python is quite easy with the free Python Development Pak. Look at this C++ code snippet for more information:
http://www.daniweb.com/code/snippet387.html
For the masochists, this might be one way to create an executable Python file. Come to think of it, you could let a Python program do the nasty detailed work!
http://www.daniweb.com/code/snippet387.html
For the masochists, this might be one way to create an executable Python file. Come to think of it, you could let a Python program do the nasty detailed work!
May 'the Google' be with you!
•
•
Join Date: Aug 2005
Posts: 148
Reputation:
Solved Threads: 6
Thanks I have forgotten to paste my solution
Here it is:
C file:
Python file:
I used MSVC++ .net v2002
i set project path to include folder in Python directory and also includede path for libraries and that was it. I placed Python file in the same project folder in MSVC++
Here it is:
C file:
Python Syntax (Toggle Plain Text)
#ifdef _DEBUG #undef _DEBUG #include "python.h" #define _DEBUG #else #include "python.h" #endif #include "python.h" #include <stdio.h> int main (int argc, char* argv[]) { double answer = 0.0; char buff [BUFSIZ]; char * p; int test = 0; PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt; fputs ("Enter expression: ",stdout); fgets (buff, sizeof buff, stdin); if (p = strrchr (buff, '\n')) { *p = '\0'; } Py_Initialize(); modname = PyString_FromString ("Test"); if (modname == NULL) { Py_Exit(0); return 0; } mod = PyImport_Import (modname); if (mod) { mdict = PyModule_GetDict (mod); func = PyDict_GetItemString (mdict, "izracunaj"); if (func) { if (PyCallable_Check (func)) { stringarg = PyString_FromString (buff); args = PyTuple_New (1); PyTuple_SetItem (args, 0, stringarg); rslt = PyObject_CallObject (func, args); if (rslt) { if (PyFloat_Check(rslt)) { answer = PyFloat_AsDouble(rslt); test = 1; } else if (PyInt_Check(rslt)) { answer = PyInt_AsLong(rslt); test = 1; } else { printf ("Nije korektan izraz!\n"); } Py_XDECREF(rslt); } Py_XDECREF(args); } } else { printf("Kivla"); } Py_XDECREF(mod); } else { printf("Python module mora biti u istom direkoriju!\n"); PyErr_Print(); } Py_XDECREF(modname); if (test) { printf("Izracunat je %g\n",answer); } return 0; }
Python file:
Python Syntax (Toggle Plain Text)
from math import * from __future__ import division def izracunaj(): x = raw_input ('Enter expression:') try: y = eval(x) except NameError: print 'Wrong expression' except: print 'error in evalution' else: print '%g' % y
I used MSVC++ .net v2002
i set project path to include folder in Python directory and also includede path for libraries and that was it. I placed Python file in the same project folder in MSVC++
•
•
Join Date: Dec 2008
Posts: 2
Reputation:
Solved Threads: 1
Hi can you help me im new in python; i tried to call python functions inside c++ and i copied your sample source code and put it in my created function. I comment out the Py_Initialize() and Py_Finalize() because they are called in different part of the program.
I put a break point in the function but the problem is when the game reads the line: func = PyDict_GetItemString(mdict, "PnlPackSel"); it returns NULL.
Any help will be appreciated
C++ Source code:
int GC_PythonCalls()
{
double answer = 0;
PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt;
// Py_Initialize();
modname = PyString_FromString("Menu");
mod = PyImport_Import(modname);
if (mod)
{
mdict = PyModule_GetDict(mod);
func = PyDict_GetItemString(mdict, "PnlPackSel"); /* borrowed reference */
if (func)
{
if (PyCallable_Check(func))
{
rslt = PyObject_CallObject(func, NULL);
if (rslt)
{
//answer = PyFloat_AsDouble(rslt);
Py_XDECREF(rslt);
OutputDebugString("PY CALL SUCCESS \n");
}
Py_XDECREF(stringarg);
Py_XDECREF(args);
}
}
Py_XDECREF(mod);
}
Py_XDECREF(modname);
//Py_Finalize();
return 0;
}
Python Code
def PnlPackSel(self):
I put a break point in the function but the problem is when the game reads the line: func = PyDict_GetItemString(mdict, "PnlPackSel"); it returns NULL.
Any help will be appreciated
C++ Source code:
int GC_PythonCalls()
{
double answer = 0;
PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt;
// Py_Initialize();
modname = PyString_FromString("Menu");
mod = PyImport_Import(modname);
if (mod)
{
mdict = PyModule_GetDict(mod);
func = PyDict_GetItemString(mdict, "PnlPackSel"); /* borrowed reference */
if (func)
{
if (PyCallable_Check(func))
{
rslt = PyObject_CallObject(func, NULL);
if (rslt)
{
//answer = PyFloat_AsDouble(rslt);
Py_XDECREF(rslt);
OutputDebugString("PY CALL SUCCESS \n");
}
Py_XDECREF(stringarg);
Py_XDECREF(args);
}
}
Py_XDECREF(mod);
}
Py_XDECREF(modname);
//Py_Finalize();
return 0;
}
Python Code
def PnlPackSel(self):
App.CtrlMouseSet(100,100)Thanks in advance
Pnl = self.PCtrlTopGet();
#bring
self.PCtrlAdd(
self.__class__.AddLvl,
(self, Pnl.ulPackId, False),
True,
);
![]() |
Similar Threads
Other Threads in the Python Forum
- Previous Thread: Reading from a website
- Next Thread: Printing out a dictionary value
Views: 13674 | Replies: 10
| Thread Tools | Search this Thread |
Tag cloud for Python
application beginner change character class client cmd code cx-freeze data database decimals development dictionary dynamic error examples excel exe file float format ftp function generator gui hack homework http import input java leftmouse library line linux list lists logging loop module mouse mysql mysqldb newb number numbers output parsing path pi port prime program programming projects push py2exe pygame pygtk pyqt python random recursion recursive redirect reverse schedule screensaverloopinactive script scrolledtext server sqlite ssh stdout string strings sudokusolver table tar terminal text thread threading time tkinter tlapse transparency tuple tutorial ubuntu unicode update urllib urllib2 variable web wikipedia windows wxpython






