Skip to content
Open
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
40 changes: 37 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ use std::{ffi::c_void, ptr::NonNull};
pub mod sys;

mod data_types;

pub use self::data_types::CastError;
use self::data_types::DLPackPointerCast;
pub use self::data_types::{CastError, DLPackPointerCast, GetDLPackDataType};

/// A managed DLPack tensor, carrying ownership of the data.
///
Expand Down Expand Up @@ -144,6 +142,42 @@ impl DLPackTensor {
}
}

/// Gets a raw mutable pointer to the underlying [`sys::DLManagedTensorVersioned`]
/// struct.
///
/// This function borrows the `DLPackTensor` and does **not** transfer
/// ownership. The `Drop` implementation of this `DLPackTensor` will
/// still run when it goes out of scope, calling the `deleter` function.
///
/// # Safety
///
/// The caller must ensure that the returned pointer does not outlive
/// this `DLPackTensor` wrapper. The caller must not call the `deleter`
/// function on this pointer, as the wrapper will do so on drop.
pub fn as_mut_ptr(&self) -> *mut sys::DLManagedTensorVersioned {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is very unsound =) It should at least take &mut self, otherwise one could get two mut pointers to the same underlying data, but I'd prefer having this function return a &mut sys::DLManagedTensorVersioned instead, so we get full lifetime tracking.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I'm not sure what's the use case is. If we want to give access to the data but not ownership, DLManagedTensorVersioned is the wrong type, that would be the job of DLTensor instead.

self.raw.as_ptr()
}

/// Consumes the tensor and returns the raw pointer to the
/// [`sys::DLManagedTensorVersioned`] struct.
///
/// # Safety
///
/// Only call this if you know you are taking ownership for FFI.
/// This function **transfers ownership** of the tensor to the caller.
///
/// The `Drop` implementation of `DLPackTensor` will **not** be called.
/// The caller is now responsible for freeing this tensor,
/// typically by passing it to a C API or another library that will
/// eventually call its `deleter` function.
///
/// Failure to call the `deleter` will result in a memory leak.
pub fn into_raw(self) -> *mut sys::DLManagedTensorVersioned {
let ptr = self.raw.as_ptr();
std::mem::forget(self);
ptr
}

/// Get a pointer to data in this tensor. This pointer can be a device
/// pointer according to [`DLPackTensor::device`].
pub fn data_ptr<T>(&self) -> Result<*const T, CastError> where T: DLPackPointerCast {
Expand Down
Loading