Search code examples
c#pointersunmanagedmanaged

int* pointer not compiling while ushort* and byte* are fine


I do have the follwing struct in a C# wrapper for some unmanaged code. I try to hand over some data using pointers, which is fine for the ushort* and byte* part, but does not work for the fixed int.

[StructLayout(LayoutKind.Sequential)]
unsafe public struct IMAGE
{
    public fixed int nSize[2];
    public ushort* pDepthIm;
    public byte* pColorIm;
}

To fill this struct with some information, I use:

unsafe public void LoadImage(ushort[] depthImage, byte[] rgbImage, int[] size)
{          
    unsafe
    {
        fixed (int* pSize = size)
        fixed (ushort* pDepth = depthImage)
        fixed (byte* pRGB = rgbImage)
        {
            _im.nSize = pSize;
            _im.pColorIm = pRGB;
            _im.pDepthIm = pDepth;

            ...
        }
     }
 }

At _im.nSize = pSize; the compiler shows an error, stating:

You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.

I already noticed that the int is initialized in a different way (not with the Pointer-*, but as fixed int), but I can't figure out how to hand over the value. When hovering over the variable, it is shown as int*...

Update: I came across the MSDN error reference for the mentioned message. I'm now sure it has to do with the fixed statement in the IMAGE struct, but I still have no idea how to fix it.


Solution

  • If found a way to access the fixed int[2] like this:

    public unsafe void LoadImage(ushort[] depthImage, byte[] rgbImage, int[] size)
    {
        unsafe
        {
            fixed (int* pSize = _im.nSize)
            fixed (ushort* pDepth = depthImage)
            fixed (byte* pRGB = rgbImage)
            fixed (S_IMAGE* pim = &_im)
            {
                pSize[0] = size[0];
                pSize[1] = size[1];
    
                _im.pColorIm = pRGB;
                _im.pDepthIm = pDepth;
            }
        }
    }
    

    Im not sure if this is a good way or if this is how it is meant to be, but at least it works as expected...