convert array to C(++) code: function body extraction?

44 views
Skip to first unread message

Nico

unread,
Jun 24, 2015, 7:23:19 AM6/24/15
to sy...@googlegroups.com
Hi everyone,

I'd like to convert a Python function that returns an array, e.g.,
def test(x, y, z):
     return [[x, y], [y, z]]
into C++ code, e.g., a function that returns a std::vector<std::vector<double>>. Right now, I call `test()` with SymPy symbols `x`, `y`, `z`, then translate every entry into C code using codegen, and then after that _regexp_ the function body out. Then from the four function bodies, I build the C++ function.

Is there a better way to do this, in particular one that works without regexping around the output code?

Cheers,
Nico

Jason Moore

unread,
Jun 24, 2015, 11:45:28 AM6/24/15
to sy...@googlegroups.com
Nico,

That's probably the quickest way to get the result you want. You can also try sublclassing the C printer and/or modifying the code generators to override the necessary parts to print the C++ you want.

If you share some of the code that you are using we can comment more specifically.

--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To post to this group, send email to sy...@googlegroups.com.
Visit this group at http://groups.google.com/group/sympy.
To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/41d60169-a7e0-49f9-9ef6-0c790bf5c7d9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ondřej Čertík

unread,
Jun 24, 2015, 1:23:19 PM6/24/15
to sympy
On Wed, Jun 24, 2015 at 5:23 AM, Nico <nico.sc...@gmail.com> wrote:
> Hi everyone,
>
> I'd like to convert a Python function that returns an array, e.g.,
>
> def test(x, y, z):
> return [[x, y], [y, z]]
>
> into C++ code, e.g., a function that returns a
> std::vector<std::vector<double>>. Right now, I call `test()` with SymPy
> symbols `x`, `y`, `z`, then translate every entry into C code using codegen,
> and then after that _regexp_ the function body out. Then from the four
> function bodies, I build the C++ function.

Also note that std::vector<std::vector<double>> will be slow, as each
row will be dynamically allocated on a heap. If you care about
efficiency, use a proper 2D array in a contiguous block of memory
(there are many libraries in C++ that provide this functionality), or
just use a single 1D std::vector<double> and index it using a 2D
indexing (i.e. i+ncol*j).

Ondrej

>
> Is there a better way to do this, in particular one that works without
> regexping around the output code?
>
> Cheers,
> Nico
>
Reply all
Reply to author
Forward
0 new messages