简体   繁体   中英

size_t compatible type for FFI

I'm writing C# bindings for a C library using unsafe code. I can't figure out how to represent a size_t that works in all cases:

  • System.[U]IntPtr can't be used with fixed-sized buffer (which I need), because they are whitelisted to only work with a few primitive types.
  • Aliasing the type with using Usize = System.Uint32/64 with compile time directives works, but a) breaks the portability of the resulting binary between architectures and b) I'd have to add the using block to everywhere that used the Usize type.

So, what is the correct way to write C bindings using size_t ?

The size_t varies depending on the platform and no C# equivalent. And .Net states that

Unfortunately there is no predefined solution for these types in .NET 2.0. So one has to be devised. The biggest issue is that you typically run the same .NET binary or 32 and 64 bit. So we need a type whose size is determined at runtime based on hints from the platform. Defining a type like this just isn't possible with .NET. The best recourse is to define a fixed size type and a custom marshaler that will make the runtime size decision.

So using UIntPtr will be your only option by aliasing the type with using Usize = System.Uint32/64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM