redeexpressos
redeexpressos
CC#
Created by redeexpressos on 1/21/2025 in #help
compile-time `IntrPtr` size for union-like structs with `FieldOffset`
hi. im developing a FFI in Rust in order to allow C# code to call methods from it. im running through an low-level issue, but maybe there is a solution. What I want to represent is something like:
enum Encryption {
NoEncryption,
EncryptionKey(*mut c_char),
EncryptionKeys(EncryptionKeys),
}
enum Encryption {
NoEncryption,
EncryptionKey(*mut c_char),
EncryptionKeys(EncryptionKeys),
}
so my idea was to represent this as the following in C#:
[StructLayout(LayoutKind.Explicit)]
public unsafe struct Encryption
{
[FieldOffset(0)]
public EncryptionTag Tag; // discriminator

[FieldOffset(4)]
public IntPtr EncryptionKey; // pointer to c string, will cast later

[FieldOffset(4)]
public IntPtr EncryptionKeys; // pointer to another struct, will cast later
}
[StructLayout(LayoutKind.Explicit)]
public unsafe struct Encryption
{
[FieldOffset(0)]
public EncryptionTag Tag; // discriminator

[FieldOffset(4)]
public IntPtr EncryptionKey; // pointer to c string, will cast later

[FieldOffset(4)]
public IntPtr EncryptionKeys; // pointer to another struct, will cast later
}
however, there is a issue. IntPtr size can differ on different architectures, which means my memory alignment offsets are wrong. I've tried [FieldOffset(4)] but compiler does not like it. Is there a good solution for this?
20 replies