Last active
September 22, 2020 05:44
-
-
Save ufcpp/eda2c50c65b3daa4ee8a0fa9bbbbc4d0 to your computer and use it in GitHub Desktop.
多次元配列の AsSpan
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
public class Program | |
{ | |
static void Main() | |
{ | |
var x = new uint[] { 0xDEADBEEF, 1, 2, 3, 4, 5, 6, 7 }; | |
var y = new uint[,] { { 0xDEADBEEF, 1, 2, 3 }, { 4, 5, 6, 7 } }; | |
var z = new uint[,,] { { { 0xDEADBEEF, 1 }, { 2, 3 } }, { { 4, 5 }, { 6, 7 } } }; | |
Write(x.AsSpan()); | |
Write(AsSpan(y)); | |
Write(AsSpan(z)); | |
} | |
// MemoryMarshal.CreateSpan が .NET Core 2.1 以降限定… | |
static Span<T> AsSpan<T>(T[,] a) => MemoryMarshal.CreateSpan(ref a[0, 0], a.Length); | |
static Span<T> AsSpan<T>(T[,,] a) => MemoryMarshal.CreateSpan(ref a[0, 0, 0], a.Length); | |
static Span<T> AsSpan<T>(Array a) | |
{ | |
// 任意ランクの Array に対して先頭要素の ref を取る手段がなさそうなので switch… | |
switch (a) | |
{ | |
case T[] x: return x.AsSpan(); | |
case T[,] x: return AsSpan(x); | |
case T[,,] x: return AsSpan(x); | |
default: throw new InvalidOperationException(); | |
} | |
} | |
static void Write<T>(Span<T> span) | |
{ | |
foreach (var x in span) | |
{ | |
Console.Write(x); | |
Console.Write(' '); | |
} | |
Console.WriteLine(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public unsafe void Send<T>(string name, Array array) | |
where T : unmanaged | |
{ | |
long[] dims = new long[array.Rank]; | |
for (int i = 0; i < dims.Length; i++) | |
{ | |
dims[i] = array.GetLength(i); | |
} | |
//一次元の長さの配列を用意 | |
var span = AsSpan<T>(array); | |
fixed (void* address = span) | |
{ | |
IntPtr npArray = NumPy.PyArrayNewFromDescr(NumPy.PyArrayType, Dtype.Int32, array.Rank, dims, null, address, NpConsts.NPY_ARRAY_CARRAY, IntPtr.Zero); | |
PyObject.SetAttr(name, npArray); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment