Memory offset of ref bool
in extern
method
#56328
-
Descriptionextern "C"
{
void MyNativeFunction(bool* flags);
} [DllImport("MyNativeLib")]
static extern void MyNativeFunction(ref bool flags);
Span<bool> flags = stackalloc bool[24576];
// more code / stackalloc in between increases the offset
MyNativeFunction(ref MemoryMarshal.GetReference(flags));
// now, values of flags seen here are offset by arbitrary number of bytes Adding Configuration.NET 6 preview 6 Linux x64 docker image from Regression?It works fine when casted to byte first, or with pointers. [DllImport("MyNativeLib")]
static extern void MyNativeFunction(ref byte flags);
Span<bool> flags = stackalloc bool[24576];
MyNativeFunction(ref MemoryMarshal.GetReference(MemoryMarshal.Cast<bool, byte>(flags))); [DllImport("MyNativeLib")]
static extern void MyNativeFunction(nint flags);
Span<bool> flags;
unsafe
{
bool* p = stackalloc bool[24576];
MyNativeFunction((nint)p);
flags = new(p, 24576);
} Other informationOffsets that actually experienced were -96 bytes and -64 bytes. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
This comment has been hidden.
This comment has been hidden.
-
I wonder if the marshaller uses a shadow copy elsewhere, passing the address of that memory location. |
Beta Was this translation helpful? Give feedback.
-
You'll either need to use In general, if you want to have the marshaller not make any copies into locals in a marshalling stub, do not use any non-blittable types. |
Beta Was this translation helpful? Give feedback.
bool
values are always marshalled when passed by value or byref
. The runtime does normalization on both managed->native and native->managed fortrue
andfalse
.You'll either need to use
bool*
(where we then assume that you know what you are doing and leave the code be), or pass as aref byte
using unsafe code.In general, if you want to have the marshaller not make any copies into locals in a marshalling stub, do not use any non-blittable types.