Complex<double> access violation, cannot understand this one!

I am calling some torchlib functions from c# and want to send some data from c# to libtorch. For this Im using torch::from_blob function with some pinned memory in c#. And it works really well, except for one case. If the data is ComplexDouble I get an access violation. But accessing the same memory with any other datatype is no problem at all.

I’ve traced the issue to assigning a complex to the memory buffer that comes from c#. But the really strange thing is that assigning anything else to this buffer is no problem at all. Only if it is a complex(double). In the code below the data is a memory corresponding to 2 complex doubles (i.e. 32 bytes).

        double* ddata = (double*)data;
        ddata[0] = 2.0;
        ddata[1] = 3.0;

        complex<float>* cfdata = (complex<float>*) data;
        cfdata[0] = complex<float>(2, 3);
        cfdata[1] = complex<float>(2, 3);

        complex<double>*cdata = (complex<double>*) data;
        cdata[0] = complex<double>(2, 3);

Running this code I get “Exception thrown at 0x00007FFFD839DF02 (cstorchlib.dll) in Examples.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.”. I get this error on the last of the lines above. And no matter what I do I cannot get an exception if I assign with some other datatype. I even tried creating my own complex double data structure and it was no problem to use.

So does anyone have any idea what is going on? Im quite lost and also surprised by the fact that I get a reading violation rather than writing.

I found the issue. c# has 8 byte aligned data (x64 mode) in arrays while complex<double> requires 16 bytes alignment. Unfortunately there is no way to make c# align to 16 bytes …