dotnet / runtimelab

This repo is for experimentation and exploring new ideas that may or may not make it into the main dotnet/runtime repo.
MIT License
1.42k stars 198 forks source link

Marshal.SizeOf and Marshal.OffsetOf #1234

Closed kant2002 closed 3 years ago

kant2002 commented 3 years ago

I learn from https://github.com/dotnet/corert/issues/5374#issuecomment-455706335 that Marshal.SizeOf(typeof(TStruct)) should be replaced with Marshal.TypeOf<TStruct>(). Does similar possibility exists for Marshal.OffsetOf ?

kant2002 commented 3 years ago

I try compile desktop application written in Eto using NativeAOT, but discover issue with GtkSharp where they use a lot of Marshal.SizeOf and Marshal.OffsetOf

jkotas commented 3 years ago

Does similar possibility exists for Marshal.OffsetOf ?

Yes, look for Marshal.OffsetOf<T>(string fieldName).

For performance, it is even better to avoid calling the Marshal.SizeOf/Offset/StructureToPtr/PtrToStructure methods and use blittable types instead. See https://docs.microsoft.com/en-us/dotnet/standard/native-interop/ . It is not always easy to refactor old code to avoid these Marshal methods.

kant2002 commented 3 years ago

Thanks!