Reputation: 1017
Following is my code snippet
class Program
{
static void Main(string[] args)
{
Program.GetState(new State() { enabled = true, currentLimit = 30 });
}
private static void GetState(State result)
{
IntPtr Ptr = Marshal.AllocHGlobal(Marshal.SizeOf(result));
Marshal.StructureToPtr(result, Ptr, false);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct State
{
[MarshalAsAttribute(UnmanagedType.I8)]
public uint currentLimit;
[MarshalAsAttribute(UnmanagedType.I1)]
public bool enabled;
}
It always throws an error i.e.
Type 'MarshellingStructureSize.State' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
My intention is to send a structure for a native DLL through pInvoke but when I try to allocate memory for my structure in Managed code through Marshal it always throw above error.
Any help would be greatly appreciated.
Upvotes: 0
Views: 2135
Reputation: 73472
uint
is actually alias for System.UInt32
which occupies 4 bytes in memory. I think currentLimit
can't be converted to 8 bytes in memory, that is why you get an error.
[MarshalAsAttribute(UnmanagedType.I8)]
public uint currentLimit;
I8
is for signed 8 byte integer. try changing it to U4
or I4
.
[MarshalAsAttribute(UnmanagedType.U4)]
public uint currentLimit;
Or change type of currentLimit
to ulong
as @Hans Passant suggested.
[MarshalAsAttribute(UnmanagedType.I8)] //or U8
public ulong currentLimit;
this works.
Upvotes: 2