Convert string to mathematical function

John Machin sjmachin at lexicon.net
Tue Aug 1 22:45:28 EDT 2006


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?

It won't "work" in the sense "you can treat that pointer exactly like a
pointer to a C++ function". You would need to embed Python in your C++
code -- read the "embedding" section of the "extending and embedding"
manual.

So far all we know is that you want Python to call C++ to call  Python
back again -- the run-time overhead and the sheer pain of getting all
that working correctly are IMHO not worth it. What is the *total*
functionality of your C++ extension? Why C++ and not C? Why C++ and not
Pyrex?

Consider doing the "extension" as a pure Python module -- Python's
built-in eval() function will certainly do the
parse-and-execute-a-formula trick for you. Even if you have extensive
compute-bound requirements, I'd suggest prototyping in Python first.

If the formula is to be executed many times and speed is a concern,
then consider using the compile() built-in to get a code object, and
see whether psyco wiil speed up its execution. I've never tried that
but it should take you much less than an hour of fiddling about to test
the idea yourself.

Hope some of this helps,
John




More information about the Python-list mailing list