using System; using System.Runtime.CompilerServices; namespace SharpGen.Runtime { public static partial class MarshallingHelpers { /// /// Instantiate a CppObject from a native pointer. /// /// The CppObject class that will be returned /// The native pointer to a com object. /// An instance of T bound to the native pointer public static T FromPointer(IntPtr cppObjectPtr) where T : CppObject => cppObjectPtr == IntPtr.Zero ? null : (T) Activator.CreateInstance(typeof(T), cppObjectPtr); /// /// Return the unmanaged C++ pointer from a instance. /// /// The type of the callback. /// The callback. /// A pointer to the unmanaged C++ object of the callback public static IntPtr ToCallbackPtr(ICallbackable callback) where TCallback : ICallbackable => callback switch { null => IntPtr.Zero, CppObject cpp => cpp.NativePointer, _ => callback.Shadow.Find(typeof(TCallback)) }; /// /// Return the unmanaged C++ pointer from a instance. /// /// The type of the callback. /// The object. /// A pointer to the unmanaged C++ object of the callback /// This method is meant as a fast-path for codegen to use to reduce the number of casts. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntPtr ToCallbackPtr(CppObject obj) where TCallback : ICallbackable => obj?.NativePointer ?? IntPtr.Zero; /// /// Return the unmanaged C++ pointer from a instance. /// /// The object. /// A pointer to the unmanaged C++ object of the callback /// This method is meant as a fast-path for codegen to use to reduce the number of casts. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntPtr ToCallbackPtr(CppObject obj) => obj?.NativePointer ?? IntPtr.Zero; } }