Argument Exception thrown by PtrToStructure
Asked Answered
F

3

6

Can someone please explain the following Argument Exception : The structure must not be a value class to me please. It's being cause by the following line of code in my program:

Marshal.PtrToStructure(m.LParam, dbh);

given that dbh is of type:

[StructLayout(LayoutKind.Sequential)]
public struct Device_Broadcast_Header
{
    public int dbch_size;
    public int dbch_devicetype;
    public int dbch_reserved;
}

Thanks

Feckless answered 28/7, 2009 at 17:56 Comment(0)
L
8

You cannot call this particular Marshal.PtrToStructure overload with a value type (i.e. a struct).

If you call this overload you can receive an instance of your type back.

Loreleilorelie answered 28/7, 2009 at 18:2 Comment(1)
For example: dbh = (Device_Broadcast_Header)Marshal.PtrToStructure(m.LParam, typeof(Device_Broadcast_Header));Caseous
T
2

Sorry for not giving a code example, but here is a link that might help you.

Here is the key text from the above link:

The problem does nothing with the RegisterTraceGuids API.

According to the doc of Marshal.PtrToStructure(IntPtr, Object) http://msdn.microsoft.com/en-us/library/30ex8z62.aspx , it throws the ArgumentException that you saw when structure layout is not sequential or explicit or structure is a boxed value type.

In this case, the structure is declared as sequential, however, the elements in the array (traceGuidReg[i]) are boxed on the managed heap because of the array object, thus you got the error "the structure must not be a value class."

You would need to use the overload Marshal.PtrToStructure Method (IntPtr, Type) http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx and assign the result of PtrToStructure to the array elements.

Tswana answered 28/7, 2009 at 18:0 Comment(1)
Thanks Jas I kind of hit the solution befor e you replied and that site also, but can you explain what thet guy meant by the elements being boxed on the Managed Heap? I think I have a fair idea what this could mean but I'd like clarification.Feckless
C
0
[StructLayout(LayoutKind.Sequential)]
public class Device_Broadcast_Header_Wrapper{
    public Device_Broadcast_Header Header
}

Device_Broadcast_Header_Wrapper wapper = new Device_Broadcast_Header_Wrapper();
Marshal.PtrToStructure(m.LParam, wapper);
Cassicassia answered 3/10, 2017 at 6:57 Comment(1)
Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have writtenPerdita

© 2022 - 2024 — McMap. All rights reserved.