5

I'm trying to make vector with 4 doubles with System.Numerics library because of SIMD. So I made this struct:

public struct Vector4D
{
    System.Numerics.Vector<double> vecXY, vecZW;

    ...

}

In this phase I code it for 128bit SIMD register. It works fine, but when I want something like this:

Vector4D* pntr = stackalloc Vector4D[8];

I get this:

Cannot take the address of, get the size of, or declare a pointer to a managed type ('Vector4D')

Any idea how to use stackalloc with System.Numerics.Vector? With System.Numerics.Vector4 (which is float-precision) there is no problem with pointers, but I need double-precision.

1 Answers1

1

I solved it:

public struct Vector4D
{
    public double X, Y, Z, W;

    private unsafe Vector<double> vectorXY
    {
        get
        {
            fixed (Vector4D* ptr = &this)
            {
                return SharpDX.Utilities.Read<Vector<double>>((IntPtr)ptr);
            }
        }
        set
        {
            fixed (Vector4D* ptr = &this)
            {
                SharpDX.Utilities.Write<Vector<double>>((IntPtr)ptr, ref value);
            }
        }
    }

    private unsafe Vector<double> vectorZW
    {
        get
        {
            fixed (Vector4D* ptr = &this)
            {
                return SharpDX.Utilities.Read<Vector<double>>((IntPtr)((double*)ptr) + 2);
            }
        }
        set
        {
            fixed (Vector4D* ptr = &this)
            {
                SharpDX.Utilities.Write<Vector<double>>((IntPtr)((double*)ptr) + 2, ref value);
            }
        }
    }
...
}

This gives you Vector for SIMD operations and also you can use pointer to struct. Unfortunately it's around 50% slower than using static array without SIMD.

  • The speed penalty you're citing comes from the `unsafe` transitions. Normally you need to amortize that cost across a much bigger chunk of SIMD work in order to realize benefits. If you are able to switch to using managed pointers instead of (unsafe) native pointers (i.e., especially now with the help C# 7.2 "ref locals"), then you will get the best of both worlds and likely see the SIMD gains you were initially hoping for. – Glenn Slayden Apr 05 '18 at 02:20