8000 Use TryGetBuffer instead of GetBuffer · pythonnet/pythonnet@6e37568 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6e37568

Browse files
committed
Use TryGetBuffer instead of GetBuffer
1 parent a058900 commit 6e37568

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

src/runtime/StateSerialization/RuntimeData.cs

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -317,21 +317,28 @@ public static void FreeSerializationData(string key)
317317
/// <param name="stream">A MemoryStream that contains the data to be placed in the capsule</param>
318318
public static void StashSerializationData(string key, MemoryStream stream)
319319
{
320-
var data = stream.GetBuffer();
321-
IntPtr mem = Marshal.AllocHGlobal(IntPtr.Size + data.Length);
322-
// store the length of the buffer first
323-
Marshal.WriteIntPtr(mem, (IntPtr)data.Length);
324-
Marshal.Copy(data, 0, mem + IntPtr.Size, data.Length);
325-
326-
try
320+
if (stream.TryGetBuffer(out var data))
327321
{
328-
using NewReference capsule = PyCapsule_New(mem, IntPtr.Zero, IntPtr.Zero);
329-
int res = PySys_SetObject(key, capsule.BorrowOrThrow());
330-
PythonException.ThrowIfIsNotZero(res);
322+
IntPtr mem = Marshal.AllocHGlobal(IntPtr.Size + data.Count);
323+
324+
// store the length of the buffer first
325+
Marshal.WriteIntPtr(mem, (IntPtr)data.Count);
326+
Marshal.Copy(data.Array, data.Offset, mem + IntPtr.Size, data.Count);
327+
328+
try
329+
{
330+
using NewReference capsule = PyCapsule_New(mem, IntPtr.Zero, IntPtr.Zero);
331+
int res = PySys_SetObject(key, capsule.BorrowOrThrow());
332+
PythonException.ThrowIfIsNotZero(res);
333+
}
334+
catch
335+
{
336+
Marshal.FreeHGlobal(mem);
337+
}
331338
}
332-
catch
339+
else
333340
{
334-
Marshal.FreeHGlobal(mem);
341+
throw new NotImplementedException($"{nameof(stream)} must be exposable");
335342
}
336343

337344
}

0 commit comments

Comments
 (0)
0