| 139 | }; |
| 140 | |
| 141 | Result<DLManagedTensor*> ExportTensor(const std::shared_ptr<Tensor>& t) { |
| 142 | // Define the DLDataType struct |
| 143 | const DataType& type = *t->type(); |
| 144 | ARROW_ASSIGN_OR_RAISE(auto dlpack_type, GetDLDataType(type)); |
| 145 | |
| 146 | // Define DLDevice struct |
| 147 | ARROW_ASSIGN_OR_RAISE(auto device, ExportDevice(t)) |
| 148 | |
| 149 | // Create TensorManagerCtx that will serve as the owner of the DLManagedTensor |
| 150 | auto ctx = std::make_unique<TensorManagerCtx>(); |
| 151 | |
| 152 | // Define the data pointer to the DLTensor |
| 153 | // If tensor is of length 0, data pointer should be NULL |
| 154 | if (t->size() == 0) { |
| 155 | ctx->tensor.dl_tensor.data = NULL; |
| 156 | } else { |
| 157 | ctx->tensor.dl_tensor.data = t->raw_mutable_data(); |
| 158 | } |
| 159 | |
| 160 | ctx->tensor.dl_tensor.device = device; |
| 161 | ctx->tensor.dl_tensor.ndim = t->ndim(); |
| 162 | ctx->tensor.dl_tensor.dtype = dlpack_type; |
| 163 | ctx->tensor.dl_tensor.byte_offset = 0; |
| 164 | |
| 165 | std::vector<int64_t>& shape_arr = ctx->shape; |
| 166 | shape_arr.reserve(t->ndim()); |
| 167 | for (auto i : t->shape()) { |
| 168 | shape_arr.emplace_back(i); |
| 169 | } |
| 170 | ctx->tensor.dl_tensor.shape = shape_arr.data(); |
| 171 | |
| 172 | std::vector<int64_t>& strides_arr = ctx->strides; |
| 173 | strides_arr.reserve(t->ndim()); |
| 174 | auto byte_width = t->type()->byte_width(); |
| 175 | for (auto i : t->strides()) { |
| 176 | strides_arr.emplace_back(i / byte_width); |
| 177 | } |
| 178 | ctx->tensor.dl_tensor.strides = strides_arr.data(); |
| 179 | |
| 180 | ctx->t = std::move(t); |
| 181 | ctx->tensor.manager_ctx = ctx.get(); |
| 182 | ctx->tensor.deleter = [](struct DLManagedTensor* self) { |
| 183 | delete reinterpret_cast<TensorManagerCtx*>(self->manager_ctx); |
| 184 | }; |
| 185 | return &ctx.release()->tensor; |
| 186 | } |
| 187 | |
| 188 | Result<DLDevice> ExportDevice(const std::shared_ptr<Tensor>& t) { |
| 189 | // Define DLDevice struct |
nothing calls this directly
no test coverage detected