forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnmanagedExtensions.cs
More file actions
57 lines (50 loc) · 2.26 KB
/
Copy pathUnmanagedExtensions.cs
File metadata and controls
57 lines (50 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Tensorflow.Util
{
public static class UnmanagedExtensions
{
//internally UnmanagedMemoryStream can't construct with null address.
private static readonly unsafe byte* _empty = (byte*)Marshal.AllocHGlobal(1);
/// <summary>
/// Creates a memory stream based on given <paramref name="address"/>.
/// </summary>
/// <param name="address">The block to stream. Can be IntPtr.Zero.</param>
/// <param name="length">The length of the block in bytes.</param>
/// <remarks>There is no need to dispose the returned <see cref="UnmanagedMemoryStream"/></remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static UnmanagedMemoryStream Stream(this IntPtr address, long length)
{
if (length <= 0)
throw new ArgumentOutOfRangeException(nameof(length));
unsafe
{
if (address == IntPtr.Zero)
return new UnmanagedMemoryStream(_empty, 0);
// ReSharper disable once AssignNullToNotNullAttribute
return new UnmanagedMemoryStream((byte*)address, length);
}
}
/// <summary>
/// Creates a memory stream based on given <paramref name="address"/>.
/// </summary>
/// <param name="address">The block to stream. Can be IntPtr.Zero.</param>
/// <param name="offset">Offset from the start of the block.</param>
/// <param name="length">The length of the block in bytes.</param>
/// <remarks>There is no need to dispose the returned <see cref="UnmanagedMemoryStream"/></remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static UnmanagedMemoryStream Stream(this IntPtr address, long offset, long length)
{
if (length <= 0)
throw new ArgumentOutOfRangeException(nameof(length));
unsafe
{
if (address == IntPtr.Zero)
return new UnmanagedMemoryStream(_empty, 0);
return new UnmanagedMemoryStream((byte*)address + offset, length);
}
}
}
}