Skip to content

Instantly share code, notes, and snippets.

@harujoh
Last active February 19, 2019 02:13
Show Gist options
  • Save harujoh/db2e43ea75729f42ec8ba15fc1055909 to your computer and use it in GitHub Desktop.
Save harujoh/db2e43ea75729f42ec8ba15fc1055909 to your computer and use it in GitHub Desktop.
Array.Reshape(param int[])で次元を変えられる拡張メソッド
internal static class ArrayExtension
{
[SuppressUnmanagedCodeSecurity]
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory(IntPtr dest, IntPtr src, int count);
public static Array Reshape(this Array array, params int[] shape)
{
Array result = Array.CreateInstance(array.GetType().GetElementType(), shape);
#if DEBUG
if (array.Length != result.Length)throw new Exception();
#endif
GCHandle source = GCHandle.Alloc(array, GCHandleType.Pinned);
GCHandle dest = GCHandle.Alloc(result, GCHandleType.Pinned);
CopyMemory(dest.AddrOfPinnedObject(), source.AddrOfPinnedObject(), Marshal.SizeOf(array.GetType().GetElementType()) * array.Length);
dest.Free();
source.Free();
return result;
}
public static Array ToNdArray<T>(this IEnumerable<T> iEnum, params int[] shape)
{
Array array = iEnum.ToArray();
Array result = Array.CreateInstance(array.GetType().GetElementType(), shape);
#if DEBUG
if (array.Length != result.Length) throw new Exception();
#endif
GCHandle source = GCHandle.Alloc(array, GCHandleType.Pinned);
GCHandle dest = GCHandle.Alloc(result, GCHandleType.Pinned);
CopyMemory(dest.AddrOfPinnedObject(), source.AddrOfPinnedObject(), Marshal.SizeOf(array.GetType().GetElementType()) * array.Length);
dest.Free();
source.Free();
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment