Skip to content

How to resolve AOT when using Marshal.PtrToStructure occurs IL2091 warnings #115140

Closed
@maikebing

Description

@maikebing

I'm having the following issue when trying to convert a piece of data to a struct

Here's an example repository: https://github.com/maikebing/115140

T BytesTo<T>(byte[] rawdatas) where T : struct
{
    var t = new T();
    int rawsize = Marshal.SizeOf<T>();
    IntPtr buffer = Marshal.AllocHGlobal(rawsize);
    Marshal.Copy(rawdatas, 0, buffer, rawsize);
    t = Marshal.PtrToStructure<T>(buffer);//  can't AOT !
    Marshal.PtrToStructure(buffer, t);// The structure must not be a value class
    Marshal.FreeHGlobal(buffer);
    return t;
}

The following code can be converted, but there will be AOT warnings .

var    t = Marshal.PtrToStructure<T>(buffer);

warning IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'System.Runtime.InteropServices.Marshal.PtrToStructure(nint)'. The generic parameter 'T' of 'BytesTo(Byte[])' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.

The following method does not have an AOT alarm, but an exception occurs.

Marshal.PtrToStructure(buffer, t);

The structure must not be a value class. (Parameter 'structure'

t = MemoryMarshal.Read<T>(rawdatas);

Cannot use type 'DF_X0_Result'. Only value types without pointers or references are supported.

Type 'DF_X0_Result'

https://github.com/maikebing/115140/blob/2f01505ff2602876166aefb75e91ffaf16c49333/Program.cs#L72

My question is, what should I do if the AOT conditions are met?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions