//==================================================================== // Read value from marshaled object (marshaled using AsAny) // It's quite slow and can return back dangling pointers // It's only there for backcompact // People should instead use the IntPtr overloads //==================================================================== private static unsafe T ReadValueSlow <T>(object ptr, int ofs, Func <IntPtr, int, T> readValueHelper) { // Consumers of this method are documented to throw AccessViolationException on any AV if (ptr == null) { throw new AccessViolationException(); } const int Flags = (int)AsAnyMarshaler.AsAnyFlags.In | (int)AsAnyMarshaler.AsAnyFlags.IsAnsi | (int)AsAnyMarshaler.AsAnyFlags.IsBestFit; MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState(); AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState)); IntPtr pNativeHome = IntPtr.Zero; try { pNativeHome = marshaler.ConvertToNative(ptr, Flags); return(readValueHelper(pNativeHome, ofs)); } finally { marshaler.ClearNative(pNativeHome); } }
/// <summary> /// Write value into marshaled object (marshaled using AsAny) and propagate the /// value back. This is quite slow and can return back dangling pointers. It is /// only here for backcompat. People should instead use the IntPtr overloads. /// </summary> private static unsafe void WriteValueSlow <T>(object ptr, int ofs, T val, Action <IntPtr, int, T> writeValueHelper) { // Consumers of this method are documented to throw AccessViolationException on any AV if (ptr is null) { throw new AccessViolationException(); } const int Flags = (int)AsAnyMarshaler.AsAnyFlags.In | (int)AsAnyMarshaler.AsAnyFlags.Out | (int)AsAnyMarshaler.AsAnyFlags.IsAnsi | (int)AsAnyMarshaler.AsAnyFlags.IsBestFit; MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = default; AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState)); IntPtr pNativeHome = IntPtr.Zero; try { pNativeHome = marshaler.ConvertToNative(ptr, Flags); writeValueHelper(pNativeHome, ofs, val); marshaler.ConvertToManaged(ptr, pNativeHome); } finally { marshaler.ClearNative(pNativeHome); } }