I think there are several approaches to achieve the behavior you want but first let me point out that it is not possible to get a function pointer of a normal Mathematica function. A function pointer would require that the function was compiled but when you define a function inside Mathematica with e.g.
f[x_,y_] := x+y;
this is not the case as Oleksandr already pointed out.
Therefore, let me first give a solution which emulates the behavior you try to achieve. If you have a MathLink program or a library function which can be used inside Mathematica you can always evaluate any kind of expressions through MathLink-communication.
The idea now is to give your C-function the name of the Mathematica function (f) you want to call together with the numeric input. The you call inside your C-function the MathKernel and evaluate the call f[x,y] and use the result in the further computation.
Assume the following short library function (it is very similar to what you have to use in your MathLink program)
#include "mathlink.h"
#include "WolframLibrary.h"
DLLEXPORT mint WolframLibrary_getVersion( ) {
return WolframLibraryVersion;
}
DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {
return 0;
}
DLLEXPORT int func(WolframLibraryData libData, mint argc, MArgument *args, MArgument res)
{
int pkt;
mreal parm1, parm2, calc_result;
char *f;
f = MArgument_getUTF8String(args[0]);
parm1 = MArgument_getReal(args[1]);
parm2 = MArgument_getReal(args[2]);
MLINK mlp = libData->getMathLink(libData);
MLPutFunction(mlp, "EvaluatePacket", 1);
MLPutFunction(mlp, f, 2);
MLPutReal(mlp, parm1);
MLPutReal(mlp, parm2);
libData->processMathLink(mlp);
pkt = MLNextPacket(mlp);
if (pkt == RETURNPKT) MLGetReal(mlp, &calc_result);
libData->UTF8String_disown(f);
MArgument_setReal(res, calc_result);
return LIBRARY_NO_ERROR;
}
Assuming you have stored this inside the file "myfunc.c" then you can create the ready-to-use library with
<< CCompilerDriver`
CreateLibrary[{"myfunc.c"}, "myfunc", "ShellOutputFunction" :> Print]
The library is automatically put to a location where it can be found by Mathematica. When you have a closer look at the func function, you see that it expects a string and two double arguments. Then it simply uses a MathLink to evaluate the function-call f[parm1,parm2] and takes the result and just passes it back.
You can load and use this function inside your current session with
f[x_, y_] := x + y;
fun = LibraryFunctionLoad["myfunc", "func", {"UTF8String", _Real, _Real}, _Real]
fun["f", 1., 4.]
(*
Out[4]= 5.
*)
fwill look in your real world application? Isfa very complicated function which uses other non-trivial Mathematica functions (e.g. special functions ). Or willfbe build from basic operations like multiplication, addition and maybe some trigonometric functions? In the first case yourfshould probably be calculated by the kernel, in the latter it's maybe possible to compile it down to a C function. – halirutan Aug 6 '12 at 21:06