Download MetaTrader 5

Question regarding string handling and DLL calls.

To add comments, please log in or register
Peter Maxwell
75
Peter Maxwell  

Can someone please clarify how string arguments are handled when calling DLL functions:


i) From what I can tell they are passed in the form of wchar_t *, in other words a pointer to a string of 16-bit wide characters.  Is there any native - in other words a function call or macro in MQL5 - to way to pass UTF-8 (multibyte) strings (it's not a massive problem as one can convert in the DLL, it would just be cleaner in certain instances)?


ii) If wanting to return a string of undetermined length from a DLL function call, what is the canonical method to go about it?

ii) a) Is it possible to return a "string" as a function result and would MQL5 free that memory (or would I need to code the DLL in such a way that it keeps state and cleans up after itself)?

ii) b) If wanting to alter a string that was passed as an argument, I assume it is impossible to resize the string?  In this instance, does the MQL5 programmer have to pass a suitably large string to accommodate all possible uses?

ii) c) Does MQL5 have any calls that will free an area of memory, i.e. can we return a pointer-to-a-pointer then free once used?


The reason I ask is that I need to pass a fair number of strings back from a DLL and the only (safe) method I can think of right now is to create a large string in MQL5 and alter that in the DLL, even then I don't know if I shorten the string whether it will cause problems by shifting the null-terminator.


I feel this is one instance where MQL5 being "like" C++ is a problem, as interacting with external libraries will invariably require more low-level functionality that is just not available, e.g. proper pointers and not some abstraction thereof.

Peter Maxwell
75
Peter Maxwell  


Ah, excellent, thanks Rosh - the conversion functions seem to answer (i), and will definitely help for calling third-party external DLLs.


Still not sure about (ii) though, as I had used that article for some basic guidance but they don't change the length of the string that is passed "by reference".

If I were to write a function in C++ of the following form (please excuse rather poor style):

extern "C" __declspec(dllexport) char * __stdcall fnTest( int stringLength ) {

   char * buffer = new char[ stringLength ];

   ZeroMemory( buffer, stringLength );

   // ... some code here that puts a legitimate wide character string into buffer

   return( buffer );

}

Would that work?  Also, would MQL5 delete[] that memory, or would a subsequent call to the DLL be required?

To add comments, please log in or register