Marshalling .NET generic types

前端 未结 2 1448
失恋的感觉
失恋的感觉 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条回答
  • 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.

    0 讨论(0)
  • 2020-12-06 18:22

    Generics as a rule are not supported in any interop scenario. Both P/Invoke and COM Interop will fail if you attempt to marshal a generic type or value. Hence I would expect Marshal.SizeOf to be untested or unsupported for this scenario as it is a marshal-specific function.

    0 讨论(0)
提交回复
热议问题