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

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

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[1], 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.

  • 1
    $\begingroup$ You can "overload" your function like MyFunction[x_Integer]:=MyFunction[N[x]]. $\endgroup$
    – Spawn1701D
    Commented Jul 4, 2013 at 16:19
  • $\begingroup$ 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! $\endgroup$
    – zakk
    Commented Jul 4, 2013 at 16:23

1 Answer 1


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.

  • 2
    $\begingroup$ +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. :)) $\endgroup$
    – rcollyer
    Commented Jul 5, 2013 at 2:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.