What is the difference between string pointers to C #?

Ok, this works:

[StructLayout(LayoutKind.Explicit, Size = 28)] public unsafe struct HandleProxy { [FieldOffset(0), MarshalAs(UnmanagedType.I4)] public JSValueType _ValueType; // JSValueType is an enum [FieldOffset(4), MarshalAs(UnmanagedType.I4)] public Int32 _ManagedObjectID; [FieldOffset(8)] public void* _NativeEngineProxy; [FieldOffset(16), MarshalAs(UnmanagedType.I4)] public Int32 _EngineID; [FieldOffset(20)] public void* _Handle; } [DllImport("Proxy")] public static extern void DisposeHandleProxy(HandleProxy* handle); 

... and this is not ...

 [StructLayout(LayoutKind.Explicit, Size = 20)] public unsafe struct ValueProxy { [FieldOffset(0), MarshalAs(UnmanagedType.I4)] public JSValueType _ValueType; // 32-bit type value. [FieldOffset(4), MarshalAs(UnmanagedType.Bool)] public bool _Boolean; [FieldOffset(4), MarshalAs(UnmanagedType.I4)] public Int32 _Integer; [FieldOffset(4)] public double _Number; [FieldOffset(12)] public void* _String; } [DllImport("Proxy")] public static extern void DisposeValueProxy(ValueProxy* valueProxy); 

So what's the difference? I'm missing something. Calling "DisposeValueProxy () gives the following error:

“Parameter # 1 cannot be marshaled”: pointers cannot refer to marshaled structures. Use ByRef instead.

(and yes, I can just use IntPtr / void * instead of "ValueProxy *", but that's not my point).

Calling "DisposeHandleProxy ()" works fine.

Let's see if anyone can figure it out.;)

+6
source share
1 answer

The string must be blittable to create a pointer to it. The second structure is not blittable, the bool field is a troublemaker. You should do this byte or int instead, depending on the intent.

An overview of which types are blittable in .NET is available here .

The exception message tip is very audible, declare the argument as ref ValueProxy instead to leave it to the pinvoke marker to create a copy of the structure with the desired location.

+8
source

Source: https://habr.com/ru/post/945445/


All Articles