Copy two-dimensional array to BitmapData.Scan0

F

frankh

With Marshal you can copy data from a one-dimensional array to
BitmapData.Scan0.

What do I do if my array is two-dimensional?

Or, alternatively, can I create somehow two variables
byte[] arr1; // size 480*640
byte[,] arr2; // size [480,640]
which are references to the same memory block and allow me to access it
at will with one or two indices, e.g. arr1[640] or arr2[1,0]?

I tried to assign arr2[0,0] to Scan0 to avoid copying at all, but it
didn't work.
 
D

Derrick Coetzee [MSFT]

With Marshal you can copy data from a one-dimensional array to
BitmapData.Scan0.

What do I do if my array is two-dimensional?

Or, alternatively, can I create somehow two variables
byte[] arr1; // size 480*640
byte[,] arr2; // size [480,640]
which are references to the same memory block and allow me to access
it at will with one or two indices, e.g. arr1[640] or arr2[1,0]?

Hi Frank. Because arrays in C# are not pointer-based, unlike in C, it is not
possible to have two arrays share the same underlying data (and in fact, I'm
not sure if multidimensional arrays even have a linear memory
representation). However, one simple solution that achieves a similar effect
is to create a class that wraps a one-dimensional array and performs index
calculations for you in an indexer like this:

public class Array2D<T> {
T[] a;
int columns;

public Array2D(int rows, int columns) {
this.columns = columns;
this.a = new T[rows * columns];
}

public T this[int row, int column] {
get {
return a[row * columns + column];
}
set {
a[row * columns + column] = value;
}
}

public T[] ToArray() {
return a;
}
}

This code is untested and uses generics, a feature of C# 2.0, but you could
use "object" in place of T at the expense of type safety and added casts.
You simply use it like a normal two-dimensional array until you want the
underlying one-dimensional array, then you call ToArray(). If the calls are
inlined, the efficiency hit should be relatively small. I hope this helps.
 
F

frankh

Well, actually I do something similar, less fancy. I simply select my
one-dimensional array element with a method "int Index (int i, int j)
which calculates a single index from an index pair. I just thought,
twodimensional arrays would be stored as a contigous series of rows in
the same way as C compilers do it. In this case, the index mapping
algorithm would already be implemented and eventually be faster than my
Index method.

The other reason was my hope that I could display an image which
already exists in the form of a bidirectional array, just redirecting a
BitmapData.Scan0 pointer to that array, without copying anything.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top