jorisvandenbossche commented on code in PR #42118:
URL: https://github.com/apache/arrow/pull/42118#discussion_r1638110951
##########
cpp/src/arrow/c/dlpack.cc:
##########
@@ -130,4 +131,63 @@ Result<DLDevice> ExportDevice(const
std::shared_ptr<Array>& arr) {
}
}
+struct TensorManagerCtx {
+ std::shared_ptr<Tensor> t;
+ 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 TensorManagerCtx 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;
+
+ ctx->tensor.dl_tensor.shape = const_cast<int64_t*>(t->shape().data());
+ std::vector<int64_t>* strides_arr = &ctx->strides;
+ strides_arr->resize(t->ndim());
+ for (int i = 0; i < t->ndim(); i++) {
+ (*strides_arr)[i] = t->strides().data()[i] / t->type()->byte_width();
+ }
Review Comment:
I am entirely sure if this was written this way for performance, but my
feeling is that this is quite complicated written, and you should also be able
to just iterate through the values in `t->strides()` and add them to
`&ctx->strides` with more standard std::vector functionality.
(for example, have a look at `FixedShapeTensorArray::FromTensor` how some of
the vectors are being created)
--
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]