From 0cd2cacd99e9c6bf28a2a9f135f9a68916bc63c2 Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Wed, 26 Jan 2022 16:47:59 +0100 Subject: [PATCH] [ObjCRuntime] Add explicit conversion operators between NativeHandle and void*. Fixes #13867. Fixes https://github.com/xamarin/xamarin-macios/issues/13867. --- src/ObjCRuntime/NativeHandle.cs | 10 +++++++ .../ObjCRuntime/NativeHandleTest.cs | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 tests/monotouch-test/ObjCRuntime/NativeHandleTest.cs diff --git a/src/ObjCRuntime/NativeHandle.cs b/src/ObjCRuntime/NativeHandle.cs index 3ae74858bf66..51374c73e2f8 100644 --- a/src/ObjCRuntime/NativeHandle.cs +++ b/src/ObjCRuntime/NativeHandle.cs @@ -66,6 +66,16 @@ public static implicit operator NativeHandle (IntPtr value) return new NativeHandle (value); } + public unsafe static explicit operator void* (NativeHandle value) + { + return (void *) (IntPtr) value; + } + + public unsafe static explicit operator NativeHandle (void * value) + { + return new NativeHandle ((IntPtr) value); + } + public override bool Equals (object? o) { if (o is NativeHandle nh) diff --git a/tests/monotouch-test/ObjCRuntime/NativeHandleTest.cs b/tests/monotouch-test/ObjCRuntime/NativeHandleTest.cs new file mode 100644 index 000000000000..89d7ea90fc50 --- /dev/null +++ b/tests/monotouch-test/ObjCRuntime/NativeHandleTest.cs @@ -0,0 +1,26 @@ +using System; + +using Foundation; +using ObjCRuntime; + +using NUnit.Framework; + +#if NET + +namespace MonoTouchFixtures.ObjCRuntime { + [TestFixture] + [Preserve (AllMembers = true)] + public class NativeHandleTest { + [Test] + public unsafe void Operators () + { + IntPtr value = new IntPtr (0xdadf00d); + + Assert.AreEqual (value, ((NativeHandle) value).Handle, "IntPtr -> NativeHandle"); + Assert.AreEqual (value, (IntPtr) new NativeHandle (value), "NativeHandle -> IntPtr"); + Assert.AreEqual (value, ((NativeHandle) ((void *) value)).Handle, "void* -> NativeHandle"); + Assert.AreEqual (value, (IntPtr) (void *) new NativeHandle (value), "NativeHandle -> void*"); + } + } +} +#endif