MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: MLPutFunction : how to put a pure function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg50050] Re: [mg49860] MLPutFunction : how to put a pure function
  • From: Omega Consulting <info at omegaconsultinggroup.com>
  • Date: Fri, 13 Aug 2004 05:55:45 -0400 (EDT)
  • References: <200408041446.KAA20186@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On Aug 4, 2004, at 9:46 AM, Zhu Chongkai wrote:

> I am writing a Mathematica FrontEnd in C using Mathlink.
>
> How to put a expression such as "Function[z,z+1][5]" (from C to
> Mathematica)?
> The standard C function 'MLPutFunction' can't do that, because the 
> head of
> the
> expression is still a compound expression but not a symbol.
>
> The same situation happens when such a expression was returned from
> Mathematica.
> Obviously, 'MLGetFunction' can't do the job.

I see 2 ways to do this:

1) Use the "text interface" of MathLink. This is where you send the 
entire expression as a sting. And Mathematica parses it, just like it 
were an In[]:=.

char buf[50]="Function[z,z+1][5]";
long numchars = strlen(buf);
MLPutNext(stdlink, MLTKFUNC);
MLPutSize(stdlink, numchars);
MLPutData(stdlink, buf, numchars);

The reverse would be

int type, num_bytes;
char* buf;
type = MLGetNext(stdlink);
MLBytesToGet(stdlink, &num_bytes);
buf = (char *)malloc(num_bytes+1);
MLGetData(stdlink, buf, num_bytes, &num_bytes);
buf[num_bytes] = '\0';

Note, all of this is boiled down code from FastBinaryFiles:
http://library.wolfram.com/infocenter/MathSource/354/

2) The second is to pull the head off and send as a separate 
expression. On the kernel side you recombine. This is equivalent to the 
kernel command:
(f = Function[z, z+1]; f[5])

MLPutFunction(stdlink, "CompoundExpression", 2);

MLPutFunction(stdlink, "Set", 2);
   MLPutSymbol(stdlink, "f");
   MLPutFunction(stdlink, "Function", 2);
   MLPutSymbol(stdlink, "z");
   MLPutFunction(stdlink, "Plus", 2);
     MLPutSymbol(stdlink, "z");
     MLPutInteger(stdlink, 1);

MLPutFunction(stdlink, "f", 1);
   MLPutInteger(stdlink, 5);

Getting is a bit trickier. Instead of returning the compound expression 
(call it x), I'd return the head and arguments separately. That is 
{Head[x], Apply[List, x]}. That's something that can be parsed by the 
standard functions.

----------------------------------------------
Omega Consulting
The final answer to your Mathematica needs.
http://omegaconsultinggroup.com


  • Prev by Date: Re: UnrankPermutation newbie problem .. Combinatorica Package
  • Next by Date: Optica question
  • Previous by thread: MLPutFunction : how to put a pure function
  • Next by thread: populate a list with random numbers from normal distribution?