2011-08-22 14 views
8

me gustaría hacer lo siguiente:múltiples Pass - matriz bidimensional de código administrado a código no administrado

  1. crear tres gama dimesinal en C# código como este:

    var myArray = new short[x,y,z]; 
    UnanagedFunction(myArray); 
    
  2. pasarlo a código no administrado (C++) de esta manera:

    void UnmanagedFunction(short*** myArray) 
    { 
        short first = myArray[0][0][0]; 
    } 
    

ACTUALIZADO Cuando intento el siguiente código tengo error de ejecución:

Attempted to read or write to protected memory.

Gracias !!!

+0

No puede escribir código como ese en C++. –

+0

la primera parte del código está en C# la segunda está en C++ y lo intenté ahora el compilador me permite el código de C++ –

+1

Tal vez puedas cambiar tu código a una matriz de triples. – Simon

Respuesta

7
IntPtr Array3DToIntPtr(short[, ,] Val) 
     { 
      IntPtr ret = Marshal.AllocHGlobal((Val.GetLength(0) + Val.GetLength(1) + Val.GetLength(2)) * sizeof(short)); 

      int offset = 0; 
      for (int i = 0; i < Val.GetLength(0); i++) 
      { 

       for (int j = 0; j < Val.GetLength(1); j++) 
       { 
        for (int k = 0; k < Val.GetLength(2); k++) 
        { 
         Marshal.WriteInt16(ret,offset, Val[i, j, k]); 
         offset += sizeof(short); 


        } 
       } 
      } 

      return ret; 
     } 

Esto ha sido probado y funciona, la única limitación es que usted tiene para llamar al Marshal.FreeHGlobal en el puntero de la matriz cuando haya terminado o se producirá una pérdida de memoria, también le sugiero que cambie su función C++ para que acepte las dimensiones de la matriz o solo podrá utilizar matrices en 3D de tamaño

+0

¡Muchas gracias! !! –

2

Lo escribo en C# puro, pero si quita el unsafe static de Func, el Func debería funcionar en C/C++. Tenga en cuenta que estoy seguro de nota seguro de que es ok ok para escribir este :-) estoy usando este Indexing into arrays of arbitrary rank in C#

static unsafe void Main(string[] args) { 
    var myArray = new short[5, 10, 20]; 

    short z = 0; 

    for (int i = 0; i < myArray.GetLength(0); i++) { 
     for (int j = 0; j < myArray.GetLength(1); j++) { 
      for (int k = 0; k < myArray.GetLength(2); k++) { 
       myArray[i, j, k] = z; 
       z++; 
      } 
     } 
    } 

    // myArray[1, 2, 3] == 243 

    fixed (short* ptr = myArray) { 
     Func(ptr, myArray.GetLength(0), myArray.GetLength(1), myArray.GetLength(2)); 
    } 
} 

// To convert to C/C++ take away the static unsafe 
static unsafe void Func(short* myArray, int size1, int size2, int size3) { 
    int x = 1, y = 2, z = 3; 
    int el = myArray[x * size2 * size3 + y * size3 + z]; // el == 243 
} 
Cuestiones relacionadas