diff --git a/Core/InteropServices/PinnedObject.cs b/Core/InteropServices/PinnedObject.cs index c02a4cde..5e088d54 100644 --- a/Core/InteropServices/PinnedObject.cs +++ b/Core/InteropServices/PinnedObject.cs @@ -21,6 +21,13 @@ namespace Vanara.InteropServices SetObject(obj); } + /// Creates a pinned object from a nullable structure. + /// The type of the structure. + /// The value to pin. + /// The offset into the pinned bytes used to return a pointer. + /// A new instance of . + public static PinnedObject FromNullable(T? obj, int offset = 0) where T : struct => obj.HasValue ? new PinnedObject(obj.Value, offset) : new PinnedObject(null, offset); + /// Initializes a new instance of the class. [ExcludeFromCodeCoverage] protected PinnedObject() { } @@ -32,7 +39,7 @@ namespace Vanara.InteropServices /// Get a pointer ( ) to the pinned memory of the object with any preset offset. /// The instance. /// The result of the conversion. - public static implicit operator IntPtr(PinnedObject ap) => ap.pinnedArray.IsAllocated ? ap.pinnedArray.AddrOfPinnedObject().Offset(ap.mOffset) : IntPtr.Zero; + public static implicit operator IntPtr(PinnedObject ap) => !ap.IsInvalid ? ap.pinnedArray.AddrOfPinnedObject().Offset(ap.mOffset) : IntPtr.Zero; /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. public void Dispose()