Re: C-pointers from Mathematica
- To: mathgroup at smc.vnet.net
- Subject: [mg113075] Re: C-pointers from Mathematica
- From: Bruno Silva <bfasilva at gmail.com>
- Date: Tue, 12 Oct 2010 04:30:41 -0400 (EDT)
Albert and Daniel, Thank you for your replies. The string pattern matching trick really does the job (and showed me several mathematica typical expressions that I was not aware of... thanks for that too!). Concerning pointer arithmetic, I haven't been programming since long but it was an habit I acquired in the past (if I well remember, that would allow to manage allocated memory dynamically... correct me if my wrong). Thanks and good luck, Bruno On Sat, Oct 9, 2010 at 11:33 AM, Albert Retey <awnl at gmx-topmail.de> wrote: > Hi, > > > I want to use Mathematica to transform a nonlinear PDE to its equivalent > > finite difference expression under a particular discretization scheme, > and > > finally export the result to a C source file. > > I manage to do the first part of the job but the problem arrives when > > translating Mathematica variable to C-program pointers. > > > > I want to transform T[x] -> * (profile + i), meaning that the value of > "T" > > at point "x" (inside Mathematica) is equivalent to the "i-th" value in > > pointer "profile" (inside file.c). > > Because Mathematica doesn't allow me to use the C-pointer sign * that > way, I > > thought replacing T[x] by a string would solve the problem ( > > T[x]->"*(profile+i)" ) but this does not work because, as soon as I apply > > CForm to the result, the string symbol "..." is kept inside the > expression I > > would like to write in file.c : > > > > T[x]/.T[x] -> "*(profile+i)" > > CForm[%] > > > > Does anyone know how to overcome this difficulty? > > I have done similar things, and for everything where the syntax is just > not available in Mathematica, I found it easiest to work with string > pattern matching of the resulting code. Here is an example: > > expr = T[5] - T[4] > > StringReplace[ > ToString[CForm[expr]], > { > "T(" ~~ x : (Except[")"] ..) ~~ ")" :> "*(profile + " <> x <> ")" > } > ] > > On the other hand I don't really see that why you want to address your > array with pointer arithmetic, from all I remember from C you could just > as well use array syntax, which would probably be easier generated from > a Mathematica expression -- and create C code that is easier to > read/debug. Here is an example of that approach (you need to change T[x] > to T[[x]] to get T[x] instead of T(x) in CForm): > > CForm[expr /. T[x_] :> T[[x]]] > > You might want to suppress the warning messages with Quiet or by > preventing the evaluation of the expression with something like this: > > CForm[Apply[HoldForm,{expr}] /. T[x_] :> T[[x]]] > > > hth, > > albert > >