Nick Vatamaniuc wrote: > Jeremy, > > Which method of extension are you using? For example you can pass the > function to C++/C directly using weave, without the need to convert to > Python first. Python has a different syntax than C++. Also I assume you > want exponentiation in you example "x^2..." and not 'xor', well, in > Python that would be "x**2" and in C you would have to include math.h > and then do pow(x,2). In other words there is no easy way to map Python > expressions to C++ (if it would be, Python could just all be mapped to > C++ and run at C++ speed!). > > Below is my attempt at using weave (I prefer pyrex myself...). Note: > this won't work too fast if your function changes on-the-fly because > each new version will need to be compiled (gcc will be called and so > on...). So it would only pay off if your function gets compiled ones > and then takes a __very__ long time to compute. > > Anyway here is my example: > -------------------------------------------------------------------------------------------- >>>> import weave >>>> includes=""" > .... #include <math.h> > .... """ >>>> c_code=""" > .... return_val=pow(a,N); > .... """ >>>> a=42 >>>> N=42 >>>> ans=weave.inline(c_code, ['a','N'], support_code=includes) > file changed > None > cc1plus: warning: command line option "-Wstrict-prototypes" is valid > for Ada/C/ObjC but not for C++ >>>> ans > 1.5013093754529656e+68 >>>> a**N > 150130937545296572356771972164254457814047970568738777235893533016064L >>>> #now call the function again. no compilation this time, the result was >>>> cached! >>>> ans=weave.inline(c_code, ['a','N'], support_code=includes) >>>> ans > 1.5013093754529656e+68 > ---------------------------------------------------------------------------------- > Look up weave for Python (it is a part of scipy) for more examples... > > Hope this helps, > Nick Vatamaniuc > > > jeremito wrote: >> I am extending python with C++ and need some help. I would like to >> convert a string to a mathematical function and then make this a C++ >> function. My C++ code would then refer to this function to calculate >> what it needs. For example I want to tell my function to calculate >> "x^2 + 3x +2", but later on I may want: "x + 3". Does anybody know how >> I can get an arbitrary string in Python (but proper mathematical >> function) turned into a C++ function? My one idea (although I don't >> know how to implement it, I'm still new at this) is to pass to C++ a >> pointer to a (Python) function. Will this work? >> Thanks, >> Jeremy > Jeremy,
I presume that you have considered and rejected use of Python's eval function. To this nonC++ user, it seems the simpler way. A someone else pointed out, you would need to import the math module. Colin W. -- http://mail.python.org/mailman/listinfo/python-list