Hi everyone,
I've developed a set of functions to manage configuration settings from an EA.
Those functions are exported by a c++ DLL and each of the exported function has the __stdcall calling convetion requested my MQL4.
My problem arises when a function need to return a string to the EA.
Naturally the function cannot:
- return a pointer to a local variabile (variable goes out of scope)
- return a pointer to a dll global variable (problems with concurrent access)
- return a pointer to a heap allocated string (need functions to free memory to be called from the EA: I don't not like this approach)
So i resolved to pass a string and string size from the EA. Es:
Code:
string buffer;
GetString( buffer, 30 );
and from the c++ dll, something like this
Code:
void __stdcall GetString( LPTSTR buffer, int BufSize )
{
// Read a string from a some source
....
// -1 to take into account the terminating null character
StringCchCopy( buffer, BufSize-1, ReadStringFromASource );
}
Here starts the weird behaviour of MQL managing strings returned from a DLL.
using the following code:
Code:
string buffer;
GetString( buffer, 30 );
the first time buffer contains the right string. A first question arises: buffer is not initialized but after calling GetString it contains the string returned. I have to suppose that MQL allocates space for a string variable when it's declared.
Next time GetString() is called the string returned seems to be truncated to the length-1 of the previous string length and not resetted as expected because of the 'string buffer;' statement.
Tried even:
Code:
string buffer = " "; // 'allocate' 30 blank characters
GetString( buffer, StringLen(buffer) );
but after the first time, when the execution returns to this code, the assignment of buffer does not work any more and buffer still contains the previous read string, and it seems it can only contains the number of characters of his content.
At first I have thought that the null character is not handled very well by MQL and modified the c++ code like this ...
Code:
CopyMemory( buffer, ReadStringFromASource, min(BufferSize,ReadStringFromASourceLength) );
and not adding the terminating null character.
But when called from MQL, no string at all is returning.
Has someone an answer ?