Narek Malkhasyan
Narek Malkhasyan

Reputation: 1442

Converting pointer to 2D array

I'm calling C++ method from C# code and passing the pointer of first element of a 2D array, and the dimensions of the array to the C++ function:

C# code

fixed (bool* addressOfMonochromeBoolMatrixOfBitmap = &monochromeBoolMatrixOfBitmap[0, 0]
{             
    NativeGetUniquenessMatrixOfBitmap(addressOfMonochromeBoolMatrixOfBitmap, Width, Height);         
}

C++ code

extern "C" __declspec(dllexport) void NativeGetUniquenessMatrixOfBitmap ( bool* addressOfMonochromeBoolMatrixOfBitmap, 
    int boolMatrixWidth, int boolMatrixHeight)
{
}

In the C++ code I want to cast the bool* pointer to 2D array, in order to access the elements using conventional array syntax: someArray[1][4]. I've tried this code:

bool (*boolMatrix)[boolMatrixWidth][boolMatrixHeight] = (bool (*)[boolMatrixWidth][boolMatrixHeight])addressOfMonochromeBoolMatrixOfBitmap;

But it doesn't compile giving the message "expected constant expression".

Please share any ideas. Thanks.

Upvotes: 1

Views: 438

Answers (1)

Al Kepp
Al Kepp

Reputation: 5980

In C++ 2D array only one array dimension can be from variable, the other one must be constant. So you have to keep the pointer and compute the address of each pixel manually.

And I am affraid you have to swap height and width, i.e. correct is probably [height][width]. If it is so, then height can be variable, but width must be constant. If it isn't constant, you have to keep the bool* pointer and compute address of each row like row = address + width*y and then you can use row[x] to access particular items in the row.

//we prepare row pointer to read at position x,y 
bool *row = addressOfMonochromeBoolMatrixOfBitmap + boolMatrixWidth * y;

//example: read from x,y
bool value_at_xy = row[x];

//example: move to next row
row += boolMatrixWidth;

Upvotes: 2

Related Questions