Passing 2D arrays to DLL and back

 

I am not an experienced programmer and looking for help here. In my expert advisor, I would like to pass a 2D array to a DLL function, modify the array and then send it back. Here is what I am doing:

In the advisor

---------------

#import "Arr.dll"
void Arr(int n1, int n2, double x[][]);
#import

#define n2 100

...

int start(){

...

int n1=1000;

double myArray[][n2];

ArrayResize(MyArray,n1);

...

Arr(n1,n2,myArray);

...

---------------

In the DLL cpp

---------------

..

MT4_EXPFUNC void __stdcall Arr( const int n1, const int n2, double ** x)

{ x[0][0]=1.0;}

---------------

MetaTrader crashes. I also tried in DLL

MT4_EXPFUNC void __stdcall Arr( const int n1, const int n2, double *x[])

and MetaTrader still crashes. The last thing to try is

MT4_EXPFUNC void __stdcall Arr( const int n1, const int n2, double *x[100])

but every time I change n2 in my expert advisor code, I will have to recompile my DLL. Please, let me know if I am doing something wrong.

 
i met the same problem, maybe mt4 doesn't support pass 2 dimension array to dll.
 
flourishing:
i met the same problem, maybe mt4 doesn't support pass 2 dimension array to dll.

It does work, but in a slightly odd - albeit quite predicable - way.


Firstly, the array has to be passed to the DLL by reference (which is also true when passing 1D arrays):


void Arr(int n1, int n2, double & x[][]);


Secondly, what the DLL gets is a pointer to a block of memory containing each value in the array. In other words, the DLL function needs to be declared something along the lines of:


void Arr(int n1, int n2, double * pFlatArrayOfDoubles)


The layout of the block of memory is that slots 0 through n-1, where n is the size of the first array dimension, contain the values for x[0][n]. After that you get x[1][n] etc. Therefore, you can get x[n1][n2] using something like the following, where n1 and n2 are zero-based:


*(pFlatArrayOfDoubles + (n1 * ArrayFirstDimensionSize) + n2)


However, this obviously means that you need to provide the DLL with not only n1 and n2, but also the size of the first dimension of the array.

Reason: