int * pointer that does not compile while ushort * and byte * are good

advertisements

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.


You can't assign a pointer to an array. You have to use memcpy.

memcpy(_im.nSize, size, sizeof(_im.nSize));

As a matter of fact you can't assign anything to an array. You can modify array's value, but not reassign it.

I would also check for the array length, pass it as a parameter or check it's .length if the languge allows it.