Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions src/TorchSharp/Tensor/Storage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,30 @@ protected static Tensor CreateTypedTensor<T>(ScalarType dtype, IList<T> rawArray
/// <summary>
/// A pointer to the raw data in memory.
/// </summary>
/// <returns></returns>
protected IntPtr data_ptr()
/// <remarks>
/// <para>
/// The returned pointer refers to the underlying storage buffer of the associated tensor. Depending on the
/// device of the tensor, this pointer may reference CPU memory or device-specific memory (for example, CUDA
/// device memory). Callers must not assume that the pointer is always CPU-accessible.
/// </para>
/// <para>
/// The lifetime of the pointer is strictly tied to the lifetime and layout of the owning tensor/storage. The
/// pointer becomes invalid if the underlying tensor or storage is moved, reallocated, resized in a way that
/// changes the underlying buffer, or disposed. Code that dereferences the pointer must ensure that the
/// associated tensor/storage instance remains alive and is not modified or disposed for the entire duration
/// of pointer use (for example, by keeping a strong reference and/or using <see cref="GC.KeepAlive(object)"/>).
/// </para>
/// <para>
/// This API is intended for advanced interop and unsafe scenarios. The pointer must not be cached and reused
/// across operations that may cause the storage to be reallocated or moved, and callers are responsible for
/// any necessary synchronization with device operations before reading from or writing to the memory.
/// </para>
/// </remarks>
/// <returns>
/// An <see cref="IntPtr"/> that points to the first element in the storage buffer. The pointer is only valid
/// while the underlying tensor/storage remains alive and its storage is not reallocated or disposed.
/// </returns>
public IntPtr data_ptr()
{
if (_tensor_data_ptr != IntPtr.Zero)
return _tensor_data_ptr;
Expand Down
14 changes: 14 additions & 0 deletions test/TorchSharpTest/TestTorchTensor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8078,6 +8078,20 @@ public void Storage_Copy()
Assert.Equal(data, x.data<long>().ToArray());
}

[Fact]
[TestOf(nameof(Tensor.storage))]
public void Storage_DataPtr()
{
var data = new float[] { 1.0f, 2.0f, 3.0f, 4.0f };
var x = torch.tensor(data);

var st = x.storage<float>();
Assert.NotNull(st);

var ptr = st.data_ptr();
Assert.NotEqual(IntPtr.Zero, ptr);
}

[Fact]
[TestOf(nameof(torch.stft))]
public void Float32STFT()
Expand Down
Loading