jorisvandenbossche commented on code in PR #42118:
URL: https://github.com/apache/arrow/pull/42118#discussion_r1638074823


##########
cpp/src/arrow/c/dlpack.cc:
##########
@@ -130,4 +131,67 @@ Result<DLDevice> ExportDevice(const 
std::shared_ptr<Array>& arr) {
   }
 }
 
+struct TensorManagerCtx {
+  std::shared_ptr<Tensor> t;
+  std::vector<int64_t> shape;
+  std::vector<int64_t> strides;
+  DLManagedTensor tensor;
+};
+
+Result<DLManagedTensor*> ExportTensor(const std::shared_ptr<Tensor>& t) {
+  // Define the DLDataType struct
+  const DataType& type = *t->type();
+  ARROW_ASSIGN_OR_RAISE(DLDataType dlpack_type, GetDLDataType(type));
+
+  // Define DLDevice struct
+  ARROW_ASSIGN_OR_RAISE(DLDevice device, ExportDevice(t))
+
+  // Create ManagerCtx that will serve as the owner of the DLManagedTensor
+  std::unique_ptr<TensorManagerCtx> ctx(new TensorManagerCtx);
+
+  // Define the data pointer to the DLTensor
+  // If tensor is of length 0, data pointer should be NULL
+  if (t->size() == 0) {
+    ctx->tensor.dl_tensor.data = NULL;
+  } else {
+    ctx->tensor.dl_tensor.data = t->raw_mutable_data();
+  }
+
+  ctx->tensor.dl_tensor.device = device;
+  ctx->tensor.dl_tensor.ndim = t->ndim();
+  ctx->tensor.dl_tensor.dtype = dlpack_type;
+
+  std::vector<int64_t>* shape_arr = &ctx->shape;
+  std::vector<int64_t>* strides_arr = &ctx->strides;
+  shape_arr->resize(t->ndim());
+  strides_arr->resize(t->ndim());
+  for (int i = 0; i < t->ndim(); i++) {
+    (*shape_arr)[i] = t->shape().data()[i];
+    (*strides_arr)[i] = t->strides().data()[i] / t->type()->byte_width();
+  }
+  ctx->tensor.dl_tensor.shape = shape_arr->data();
+  ctx->tensor.dl_tensor.strides = strides_arr->data();
+  ctx->tensor.dl_tensor.byte_offset = 0;
+
+  ctx->t = std::move(t);
+  ctx->tensor.manager_ctx = ctx.get();
+  ctx->tensor.deleter = [](struct DLManagedTensor* self) {
+    delete reinterpret_cast<ManagerCtx*>(self->manager_ctx);

Review Comment:
   ```suggestion
       delete reinterpret_cast<TensorManagerCtx*>(self->manager_ctx);
   ```
   
   That might fix the memory leak?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to