C# calling unmanaged code. Does the ref-keyword fix memory location of variable?

120 views Asked by At

when calling unmanaged code from C# I often see memory pinned (which I understand why we do that) but I also see the ref-keyword being used. Now, I wonder why wouldn't we here need some memory pinning as well?

Edit: for simplicity let's assume the external code does not store the pointers for later use.

internal class Program
{
    // extern void multiply(BoxT * box, const double O[3]);
    [DllImport("vectorMaths.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern void multiply(ref BoxT box, double[] O);

    [StructLayout(LayoutKind.Sequential)]
    struct BoxT
    {
        public double[] O; // origin of box in coordinate system
        public double[] A; // adjacent corner 1
        public double[] B; // adjacent corner 2
        public double[] C; // adjacent corner 3
    }

    static void Main(string[] args)
    {
        // create box
        var BoxT = new BoxT
        {
            O = new double[] { 1, 1, 1 }, // origin of box in coordinate system
            A = new double[] { 2, 1, 1 }, // adjacent corner 1
            B = new double[] { 1, 2, 1 }, // adjacent corner 2
            C = new double[] { 1, 1, 2 }, // adjacent corner 3
        };
        var deformation = new double[] { 1, 2, 3 };

        // call C function to deform box. Wouldn't I need to pin memory locations here?
        multiply(ref BoxT, deformation);
    }
}
0

There are 0 answers