2011-08-22 15 views
8

vorrei fare quanto segue:Multi Pass - matrice bidimensionale da codice gestito a codice non gestito

  1. creare tre serie dimesinal in codice C# in questo modo:

    var myArray = new short[x,y,z]; 
    UnanagedFunction(myArray); 
    
  2. passarlo a codice non gestito (C++) in questo modo:

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

AGGIORNATO Quando provo il seguente codice che ho errore di runtime:

Attempted to read or write to protected memory.

Grazie !!!

+0

Non è possibile scrivere codice come quello in C++. –

+0

la prima parte del codice è in C# la seconda è in C++ e l'ho provata ora il compilatore mi consente il codice C++ –

+1

Forse puoi cambiare il tuo codice in una serie di triple. – Simon

risposta

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; 
     } 

Questo è stato testato e funziona, l'unica limitazione è che avete per chiamare Marshal.FreeHGlobal sul puntatore dell'array quando hai finito con esso o otterrai una perdita di memoria, ti suggerirei anche di cambiare la tua funzione C++ in modo che accetti le dimensioni dell'array o sarai in grado di usare solo array 3d di specifici dimensione

+0

Grazie mille! !! –

2

Lo sto scrivendo in puro C#, ma se togli il unsafe static da Func, lo Func dovrebbe funzionare in C/C++. Si tenga presente che io sono sicuro nota sicuro che sia ok ok a scrivere questo :-) sto usando questo 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 
} 
Problemi correlati