Passing strings between MQL and C++ DLL

MetaTrader

MetaTrader is a popular platform used for forex trading, and other financial products trading (stock, commodity…) It provides to user the ability to add more features to the platform using its own language MQL. You can program your own indicator and your expert advisor to work with MetaTrader. The powerful of MQL is that it can call a Windows DLL library, so that you can add any feature to your program.

Passing strings to exchange data between MQL and Windows DLL is the most difficult problem. How to exchange data buffer without causing MetaTrader crash? This can achieve by allocating buffer memory within MetaTrader, then pass its pointer to DLL. MetaTrader then has the rights to free the allocated memory. If the memory is allocated by DLL, MetaTrader can’t free it and it causes crashing problems or memory leak.

Here is an example about exchange a string using buffer memory:

Passing strings from MQL to C++ DLL

* MQL:

#import “MT4.dll”
void sendText(char&[]);
#import

char buffer[10240];
StringToCharArray(“Hello World”, buffer);
sendText(buffer);

* C++ DLL:

#define MT4EXPORT extern “C” __declspec(dllexport)

MT4EXPORT void sendText(char* buffer){
// do something with ‘buffer’
}

Passing strings from C++ DLL to MQL

* C++ DLL:

#define MT4EXPORT extern “C” __declspec(dllexport)
MT4EXPORT void getText(char* buffer){
char* text = “Hello World”;
strcpy(buffer, text);
}

* MQL:

#import “MT4.dll”
void getText(char&[]);
#import

char buffer[10240];

getText(buffer);
string text=CharArrayToString(buffer);
Print(text);


Leave a Reply