Function Pointers in MQL5

Does MQL5 support Function Pointers? I think i saw it in the change log.

not added to documentation yet, just in list of changes

MQL5: Added support for pointers to functions to simplify the arrangement of event models.

To declare a pointer to a function, specify the “pointer to a function” type, for example:

typedef int (*TFunc)(int,int);

Now, TFunc is a type, and it is possible to declare the variable pointer to the function:

TFunc func_ptr;

The func_ptr variable may store the function address to declare it later:

int sub(int x,int y) { return(x-y); }
int add(int x,int y) { return(x+y); }
int neg(int x)       { return(~x);  }



func_ptr=neg;           // error: neg is not of  int (int,int) type
Print(func_ptr(10));    // error: there should be two parameters

Pointers to functions can be stored and passed as parameters. You cannot get a pointer to a non-static class method.‌

Great, thanks! I knew I’d seen it somewhere.

N‌ow if we can just get lambda expressions too… :slight_smile:

Any way to use function templates with function pointers, to create generic method delegates?

Works in MT4 too

If this can be added, we then can implement the general delegate type equivalents from C#:

void Action<TInput1, TInput2, TInput3...>
TReturn Func<TReturn, TInput1, TInput2, TInput3...>

and this then enables Linq-style operations like Where, SingleOrDefault, OrderBy etc, without having to wrap anything you want to work with first in a CObject-derived type


has anyone tried passing a callback as a parameter to an exported dll function? I tried, but it seems MQL5 uses a totally different type. On a 64-bit MT5 installation the size of an MQL function pointer is 4 (bytes), whereas the size of a C++ function pointer is 8. Anyone know how they are stored?


MQL pointers are handles not addresses. C/C++ pointers are addresses.

Is there a matching C/C++ datatype for handles? Or is it simply not possible to call MQL functions from a dll using callbacks?