CSharp examples for System:Array Element
Managed Array From Numpy Array
using System.Runtime.InteropServices; using System.Reflection; using System.Text; using System.Linq; using System.Collections.Generic; using System.Collections; using System;// w ww .j av a 2 s. c o m public class Main{ public unsafe static Array ManagedArrayFromNumpyArray(object numpyArray) { Array managedArray; dynamic dynamicArray = numpyArray; dynamic newArray = null; int[] dimensions = new int[dynamicArray.Dims.Length]; int length = 1; for (int i = 0; i < dimensions.Length; ++i) { dimensions[i] = (int)dynamicArray.Dims[i]; length *= dimensions[i]; } // Treat double precision data as special case and keep everything fast. if (dynamicArray.dtype.name == "float64") { try { // If necessary get a contiguous, C-type double precision array: if (!dynamicArray.flags.contiguous) { newArray = dynamicArray.copy("C"); } } catch (Exception) { throw new Exception("Failed to change input array into contiguous array."); } IntPtr start; if (newArray == null) start = dynamicArray.UnsafeAddress; else start = newArray.UnsafeAddress; if (dimensions.Length == 1) { managedArray = new double[dimensions[0]]; fixed (double* newArrayPointer = (double[])managedArray) { double* currentPosition = newArrayPointer; double* numpyPointer = (double*)start; double* endPointer = newArrayPointer + length; while (currentPosition != endPointer) { *currentPosition = *numpyPointer; currentPosition++; numpyPointer++; } } } else if (dimensions.Length == 2) { managedArray = new double[dimensions[0], dimensions[1]]; fixed (double* newArrayPointer = (double[,])managedArray) { double* currentPosition = newArrayPointer; double* numpyPointer = (double*)start; double* endPointer = newArrayPointer + length; while (currentPosition != endPointer) { *currentPosition = *numpyPointer; currentPosition++; numpyPointer++; } } } else { throw new Exception("Array must be one or two dimensionsal."); } if (newArray != null) newArray.Dispose(); } else { managedArray = Array.CreateInstance(typeof(double), dimensions); IndexEnumerator enumerator = new IndexEnumerator(dimensions); while (enumerator.MoveNext()) { managedArray.SetValue(dynamicArray.item(enumerator.CurrentObjectIndices), enumerator.CurrentIndices); } } return managedArray; } }