Download MetaTrader 5
To add comments, please log in or register
Having troubles understanding the code? Perhaps, you can find an article on that topic!
supermartzin 2016.08.03 13:45 

I am writing a script in MQL4 language for Metatrader 4 which is using C# DLL library for further data processing.


What I'm trying to do is to pass an array of following MQL structures:

struct marketUpdate
    double openPrice;
    double closePrice;
    double highPrice;
    double lowPrice;
    int volume;
    double pipValuePerLot;
    int intervalLength;
    string symbol;
    string time;

 to this function in C# DLL:

[DllExport("HistoricMarketData", CallingConvention.StdCall)]
public static int HistoricMarketData(
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] MarketUpdate[] unmanagedArray,
    int length)
    // further processing

 This is the function definition on MQL side:

 int HistoricMarketData(
          marketUpdate &marketUpdates[],
          int length);

 and this is the structure on C# side:

public struct MarketUpdate
    public double openPrice;

    public double closePrice;

    public double highPrice;

    public double lowPrice;

    public int volume;

    public double pipValuePerLot;

    public int intervalLength;

    public string symbol;

    public string time;


My problem is that it is not working when calling HistoricMarketData from MQL. The script either crashes whole Metatrader program or throws an exception and fails.

As you can see I'm using Robert Giesecke's Unmanaged Exports library to make it works and I correctly imported DLL to MQL as other functions inside are working without any issue.

After lot of trial and error I was able to find out that when I remove those 2 string attributes (symbol and time) from structure all works as expected and structure is correctly passed to C# function.

So my question is how to correctly pass string in structure from MQL to C#?

I already tried to change UnmanagedType parameter at MarshalAs annotation in structure to other string variants but it didn't help. It also didn't help to change string to char[] on both sides.

I'll appreciate any advices or help.

To add comments, please log in or register