Marshal.PtrToStructure complains about Null Reference

J

John

public const int FRAME_LENGTH=144;
[StructLayout(LayoutKind.Sequential, Pack=1)]
public class FRAME_T
{
public byte []Block = new byte[FRAME_LENGTH]; }

public void MyDataHandler(IntPtr appContext, IntPtr data)
FRAME_T frame = new FRAME_T();
Marshal.PtrToStructure(data, frame);

This code throws an exception on the PtrToStructure saying there is a
null reference.

What am I doing wrong?

THANKS!!!

John
 
G

Guest

Hi John,

I can only guess at what is going wrong. I see two possible errors. One
being that the array is managed and not of constant length. The other being
that you use a class instead of a struct. Perhaps you should try the
following:

[ StructLayout( LayoutKind.Sequential, Pack = 1 ) ]
public struct Frame_t
{
[ MarshalAs( UnmanagedType.ByValArray,
ArraySubType = UnmanagedType.U1,
SizeConst = 144 ) ]
public byte[] Block;
}

//...
public void MyDataHandler( IntPtr appContext, IntPtr data )
{
Frame_t frame = ( Frame_t ) Marshal.PtrToStructure (
data,
typeof( Frame_t )
);
// ...
}

That should work.

HTH,
Tom T.
 
J

John

Dude, you rock!!!! THANK YOU!!! That worked. I spent over 4 hours
yesterday trying to make this work and I couldn't figure it out.

Please email your mailing address to me so that I may send you a gift.

THANK YOU! THANK YOU!

John

TT (Tom Tempelaere) said:
Hi John,

I can only guess at what is going wrong. I see two possible errors. One
being that the array is managed and not of constant length. The other being
that you use a class instead of a struct. Perhaps you should try the
following:

[ StructLayout( LayoutKind.Sequential, Pack = 1 ) ]
public struct Frame_t
{
[ MarshalAs( UnmanagedType.ByValArray,
ArraySubType = UnmanagedType.U1,
SizeConst = 144 ) ]
public byte[] Block;
}

//...
public void MyDataHandler( IntPtr appContext, IntPtr data )
{
Frame_t frame = ( Frame_t ) Marshal.PtrToStructure (
data,
typeof( Frame_t )
);
// ...
}

That should work.

HTH,
Tom T.

John said:
public const int FRAME_LENGTH=144;
[StructLayout(LayoutKind.Sequential, Pack=1)]
public class FRAME_T
{
public byte []Block = new byte[FRAME_LENGTH]; }

public void MyDataHandler(IntPtr appContext, IntPtr data)
FRAME_T frame = new FRAME_T();
Marshal.PtrToStructure(data, frame);

This code throws an exception on the PtrToStructure saying there is a
null reference.

What am I doing wrong?

THANKS!!!

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top