mercredi 6 septembre 2017

C# fill array of struct with random data

For testing purposes, I want to do the following thing:

class ArrayOfStructWithRandomData<T> where T : struct {
  private T[] array;

  ArrayOfStructWithRandomData() {
    array = new T[1000000];
    InitializeArrayToRandomData();
  }
}

How could I implement InitializeArrayToRandomData() without using the 'unsafe' keyword?

One idea was to use Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T)) * 1000000) to allocate a chunk of unmanaged memory, then use Marshal.Copy(Byte[], Int32, IntPtr, Int32) to fill that memory with random data and then use something like

static T[] GetArrayFromNativePointer<T>(IntPtr unmanaged_memory, int length) {
  T[] result = new T[length];
  if (IntPtr.Size == 4) {
    int size = Marshal.SizeOf(typeof(T));

    // 32-bit system.
    for (int i = 0; i < result.Length; i++) {
      result[i] = (T)Marshal.PtrToStructure(array, typeof(T));
      array = new IntPtr(array.ToInt32() + size);
    }
  } else {
    long size = Marshal.SizeOf(typeof(T));

    // Probably 64-bit system.
    for (int i = 0; i < result.Length; i++) {
      result[i] = (T)Marshal.PtrToStructure(array, typeof(T));
      array = new IntPtr(array.ToInt64() + size);
    }
  }
  return result;
}

Is there a better way?




Aucun commentaire:

Enregistrer un commentaire