# MathLink and a function of a real variable

I am trying to use a real function of a real variable written in C from Mathematica, my .tm file reads as follows:

:Begin:
:Function:       my_function
:Pattern:        MyFunction[ x_Real]
:Arguments:      { x }
:ArgumentTypes:  { Real }
:ReturnType:     Real
:End:

double my_function(double x) { /* snip */ return ret; }


I can compile with mcc, install the program from within Mathematica, and call my function as MyFunction[1.0], but it won't work if I call it with an integer argument, like MyFunction, as it is not automatically converted to a Real and then to a double.

How can I make my function work well also with integer arguments?

Also I have to apply some numerical Mathematica methods (like NMinimize, NIntegrate) and they fail when evaluating the function for integer values.

• You can "overload" your function like MyFunction[x_Integer]:=MyFunction[N[x]]. – Spawn1701D Jul 4 '13 at 16:19
• That's what I need, I thought that N[integer] would remain an integer, but this is not the case. If you want to convert your comment into an answer I will accept it. Thank you! – zakk Jul 4 '13 at 16:23

When your C-function takes a double argument, then your template definition is not optimal, because the pattern x_Real forbids you to put anything else than a real number.

It's far more general if your function can take all arguments which can be converted into a real number. Two steps are required for this. First, you change your pattern to

:Pattern:        MyFunction[ x_?NumericQ]


which lets you even call your function with Pi or 1 or 1/E. Second thing, and this is probably not widely known: the :Arguments: section can evaluate code! Therefore, you can make the transition to a real number there:

:Arguments:      { N[x] }


Now you can call your MathLink function without a wrapper, because things like 1, Pi and 2/3 are converted automatically.

• +1, for the info on the :Arguments: section, alone. (The rest could be deserving of an upvote, also, but you'll have to work harder. :)) – rcollyer Jul 5 '13 at 2:35