Marshalling .NET generic types

前端 未结 2 1453
失恋的感觉
失恋的感觉 2020-12-06 17:35

Here is a C# program that tries Marshal.SizeOf on a few different types:

using System;
using System.Runtime.InteropServices;

[StructLayout(Layo         


        
2条回答
  •  萌比男神i
    2020-12-06 18:07

    It is not known what size the aggregated object T would have (it would be the size of a pointer if T is a referenece type and mostly any value if it is value type).

    I think you can solve this problem by setting the MarshalAs attribute on the field 'value' specifying the most matching type (for example, Unmanagedtype.SysInt). Note that it still won't work for so-called non-mappable types (i.e. types for which fields offsets and sizes can't be deduced easily).

    But AFAIK, it's not recommended to use generics in interop.

提交回复
热议问题