|
2 | 2 | * SPDX-License-Identifier: Apache-2.0 |
3 | 3 | */ |
4 | 4 |
|
5 | | -#include <pybind11/pybind11.h> |
6 | | -#include <pybind11/stl.h> |
| 5 | +#include <nanobind/nanobind.h> |
| 6 | +#include <nanobind/stl/string.h> |
| 7 | +#include <nanobind/stl/vector.h> |
7 | 8 |
|
8 | | -#include "onnx/py_utils.h" |
9 | 9 | #include "onnxoptimizer/model_util.h" |
10 | 10 | #include "onnxoptimizer/optimize.h" |
11 | 11 |
|
12 | 12 | namespace ONNX_NAMESPACE { |
13 | | -namespace py = pybind11; |
14 | | -using namespace pybind11::literals; |
15 | | -PYBIND11_MODULE(onnx_opt_cpp2py_export, onnx_opt_cpp2py_export) { |
| 13 | +namespace nb = nanobind; |
| 14 | +using namespace nanobind::literals; |
| 15 | + |
| 16 | +template <typename Proto> |
| 17 | +bool ParseProtoFromPyBytes(Proto* proto, const nb::bytes& bytes) { |
| 18 | + // Get the buffer from Python bytes object |
| 19 | + char* buffer = nullptr; |
| 20 | + Py_ssize_t length = 0; |
| 21 | + PyBytes_AsStringAndSize(bytes.ptr(), &buffer, &length); |
| 22 | + |
| 23 | + return ParseProtoFromBytes(proto, buffer, length); |
| 24 | +} |
| 25 | + |
| 26 | +NB_MODULE(onnx_opt_cpp2py_export, onnx_opt_cpp2py_export) { |
16 | 27 | onnx_opt_cpp2py_export.doc() = "ONNX Optimizer"; |
17 | 28 |
|
18 | 29 | onnx_opt_cpp2py_export.def( |
19 | 30 | "optimize", |
20 | | - [](const py::bytes& bytes, const std::vector<std::string>& names) { |
| 31 | + [](const nb::bytes& bytes, const std::vector<std::string>& names) { |
21 | 32 | ModelProto proto{}; |
22 | 33 | ParseProtoFromPyBytes(&proto, bytes); |
23 | 34 | auto const result = optimization::Optimize(proto, names); |
24 | 35 | std::string out; |
25 | 36 | result.SerializeToString(&out); |
26 | | - return py::bytes(out); |
| 37 | + return nb::bytes(out.data(), out.size()); |
27 | 38 | }); |
28 | 39 |
|
29 | 40 | onnx_opt_cpp2py_export.def( |
30 | 41 | "optimize_fixedpoint", |
31 | | - [](const py::bytes& bytes, const std::vector<std::string>& names) { |
| 42 | + [](const nb::bytes& bytes, const std::vector<std::string>& names) { |
32 | 43 | ModelProto proto{}; |
33 | 44 | ParseProtoFromPyBytes(&proto, bytes); |
34 | 45 | auto const result = optimization::OptimizeFixed(proto, names); |
35 | 46 | std::string out; |
36 | 47 | result.SerializeToString(&out); |
37 | | - return py::bytes(out); |
| 48 | + return nb::bytes(out.data(), out.size()); |
38 | 49 | }); |
39 | 50 |
|
40 | 51 | onnx_opt_cpp2py_export.def( |
|
0 commit comments