diff --git a/src/NodeApi/JSTypedArray.cs b/src/NodeApi/JSTypedArray.cs index 86ea6e3d..e961da9f 100644 --- a/src/NodeApi/JSTypedArray.cs +++ b/src/NodeApi/JSTypedArray.cs @@ -106,26 +106,13 @@ public unsafe JSTypedArray(ReadOnlyMemory data) /// returns that JS value. /// /// The JS value, or null if the memory is external to JS. - private static unsafe JSValue? GetJSValueForMemory(ReadOnlyMemory data) + private static JSValue? GetJSValueForMemory(ReadOnlyMemory data) { - // This assumes the owner object of a Memory struct is stored as a reference in the - // first (private) field of the struct. If the Memory internal structure ever changes - // (in a future major version of the .NET Runtime), this unsafe code could crash. - // Unfortunately there's no public API to get the Memory owner object. - void* memoryPointer = Unsafe.AsPointer(ref data); - object? memoryOwner = Unsafe.Read(memoryPointer); - if (memoryOwner is MemoryManager manager) + if (MemoryMarshal.TryGetMemoryManager(data, out MemoryManager? manager, out int index, out int length)) { // The Memory was created from a JS TypedArray. - // Strip the high bit of the index - it has a special meaning. - void* memoryIndexPointer = (byte*)memoryPointer + Unsafe.SizeOf(); - int index = Unsafe.Read(memoryIndexPointer) & ~int.MinValue; - - void* memoryLengthPointer = (byte*)memoryIndexPointer + Unsafe.SizeOf(); - int length = Unsafe.Read(memoryLengthPointer); - - JSValue value = manager.JSValue; + JSValue value = manager!.JSValue; int valueLength = value.GetTypedArrayLength(out _); if (index != 0 || length != valueLength)