Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Marshal.SizeOf(strurtretype)总是抛出错误_C#_C++_.net_Pinvoke - Fatal编程技术网

C# Marshal.SizeOf(strurtretype)总是抛出错误

C# Marshal.SizeOf(strurtretype)总是抛出错误,c#,c++,.net,pinvoke,C#,C++,.net,Pinvoke,下面是我的代码片段 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(Mar

下面是我的代码片段

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;
}
它总是抛出一个错误,即

无法将类型“MarshellingStructureSize.State”封送为 非托管结构;无法计算有意义的大小或偏移量

我的意图是通过pInvoke发送本机DLL的结构,但当我试图通过封送为托管代码中的结构分配内存时,它总是抛出上述错误


任何帮助都将不胜感激

uint
实际上是
System.UInt32
的别名,它在内存中占用4个字节。我认为
currentLimit
无法在内存中转换为8字节,这就是为什么会出现错误

[MarshalAsAttribute(UnmanagedType.I8)]
public uint currentLimit;
I8
用于有符号8字节整数。尝试将其更改为
U4
I4

[MarshalAsAttribute(UnmanagedType.U4)]
public uint currentLimit;
或者按照@Hans Passant的建议,将
currentLimit
的类型更改为
ulong

[MarshalAsAttribute(UnmanagedType.I8)] //or U8 
public ulong currentLimit;

这是.

,因为它与调用本地DLL有部分关系,因此有用的点也可以来自C++社区。问题是CurrimeLimestMalSalasAttor(unMaundType。i8)。C#中的uint只有4字节大小。将属性更改为UnmangedType.U4.Right,或将其设置为ulong。@当然是HansPassant,这取决于OP的需要。:)我会更新我的答案,谢谢