I am trying to call Mathematica 10 from F#. Following the C# sample code found in the Mathematica directory, I have written the following F# code:

type TestClass() =
    member this.AddNumsWithWM (m : int) (n : int) : int =
        let ml = MathLinkFactory.CreateKernelLink()
        ml.PutFunction("EvaluatePacket", 1)
        ml.PutFunction("testFunc", 2) // IF BUILT-IN FUNCTION LIKE Plus, THEN NO ERROR
        ml.WaitForAnswer() |> ignore
        let res = ml.GetInteger() // THE ERROR OCCURS HERE FOR CUSTOM FUNCTION

The Mathematica function testFunc is simply:

testFunc[m_Integer, n_Integer] := m + 2 * n;

But when I call the function AddNumsWithWM 2 3, I get the following error at the line indicated above:

Wolfram.NETLink.MathLinkException was unhandled
Message: An unhandled exception of type 'Wolfram.NETLink.MathLinkException' occurred in Wolfram.NETLink.dll
Additional information: Error code: 3.

I don't understand, because the sample C#, from which this has been translated literally, works. Any idea why I would get the above error?

Thanks in advance for your help.


I have verified something else. If I use a built-in function like Plus instead of my custom function testFunc, the code works.

So, then, I guess my question would be, Why does the code not work for a custom function? I would be very grateful for pointers on what I need to do differently in order to call a custom function.

I have edited the question accordingly.

  • 1
    $\begingroup$ Have you solved this problem?I also face the problem in .NETLink programing. and i realize that even a built-in function like Plus can not be used like the sample in the document of .NETLink API. If you have solve the problem, can you give me some advice?Thank U $\endgroup$
    – yyteen
    Commented Oct 26, 2014 at 15:58

1 Answer 1


testFunc[] needs to be defined prior to being called. I don't use .NETLink, so I can't guarantee if the following will work, but try ml.Evaluate("testFunc[m_Integer, n_Integer] := m + 2 * n;") to do so. I'm not sure if this returns any packets and needs to be followed up with an ml.WaitAndDiscardAnswer(). In any case, if you have many custom functions, I suggest putting them in a package to be loaded via an ml.Evaluate("Get[package];") to reduce overhead from multiple .NETLink calls.


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.