From 77c2e56d825207e51c26bf7961d269a09af3f924 Mon Sep 17 00:00:00 2001 From: Eric Cousineau Date: Fri, 10 Nov 2023 17:21:54 -0500 Subject: [PATCH] Pure pybind example of overload failure --- tmp/BUILD.bazel | 14 ++++++++++++ tmp/cc_py.cc | 54 +++++++++++++++++++++++++++++++++++++++++++++++ tmp/cc_py_test.py | 23 ++++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 tmp/BUILD.bazel create mode 100644 tmp/cc_py.cc create mode 100644 tmp/cc_py_test.py diff --git a/tmp/BUILD.bazel b/tmp/BUILD.bazel new file mode 100644 index 000000000000..6116f4fc28f2 --- /dev/null +++ b/tmp/BUILD.bazel @@ -0,0 +1,14 @@ +load("//tools/skylark:pybind.bzl", "pybind_py_library") + +pybind_py_library( + name = "cc_py", + cc_so_name = "cc", + cc_srcs = ["cc_py.cc"], + py_imports = ["."], +) + +py_test( + name = "cc_py_test", + srcs = ["cc_py_test.py"], + deps = [":cc_py"], +) diff --git a/tmp/cc_py.cc b/tmp/cc_py.cc new file mode 100644 index 000000000000..9bf1da392e08 --- /dev/null +++ b/tmp/cc_py.cc @@ -0,0 +1,54 @@ +#include "pybind11/eigen.h" +#include "pybind11/pybind11.h" + +namespace py = pybind11; + +namespace drake { + +struct MyScalar { + int value{}; +}; + +} // namespace drake + +PYBIND11_NUMPY_OBJECT_DTYPE(drake::MyScalar); + +namespace drake { +namespace { + +std::string AcceptMatrixDense(const Eigen::MatrixXd&) { + return "dense"; +} + +std::string AcceptMatrixSparse(const Eigen::SparseMatrix&) { + return "sparse"; +} + +using VectorXMyScalar = Eigen::Matrix; + +std::string AcceptMatrixAndObjectDense( + const Eigen::MatrixXd&, const VectorXMyScalar&) { + return "dense"; +} + +std::string AcceptMatrixAndObjectSparse( + const Eigen::SparseMatrix&, const VectorXMyScalar&) { + return "sparse"; +} + +// Try to replicate signature as in #20516. + +PYBIND11_MODULE(cc, m) { + m.def("AcceptMatrix", &AcceptMatrixDense); + m.def("AcceptMatrix", &AcceptMatrixSparse); + + py::class_(m, "MyScalar") + .def(py::init(), py::arg("value")) + .def_readwrite("value", &MyScalar::value); + + m.def("AcceptMatrixAndObject", &AcceptMatrixAndObjectSparse); + m.def("AcceptMatrixAndObject", &AcceptMatrixAndObjectDense); +} + +} // namespace +} // namespace drake diff --git a/tmp/cc_py_test.py b/tmp/cc_py_test.py new file mode 100644 index 000000000000..3bb684bc0a50 --- /dev/null +++ b/tmp/cc_py_test.py @@ -0,0 +1,23 @@ +import unittest + +import numpy as np +import scipy.sparse + +from drake.tmp.cc import AcceptMatrix, AcceptMatrixAndObject, MyScalar + + +class Test(unittest.TestCase): + def test_overload(self): + A_dense = np.eye(2) + A_sparse = scipy.sparse.csc_matrix(np.eye(2)) + self.assertEqual(AcceptMatrix(A_dense), "dense") + self.assertEqual(AcceptMatrix(A_sparse), "sparse") + + x = np.array([MyScalar(1), MyScalar(2)]) + self.assertEqual(x.dtype, object) + self.assertEqual(AcceptMatrixAndObject(A_dense, x), "dense") + self.assertEqual(AcceptMatrixAndObject(A_sparse, x), "sparse") + + +if __name__ == "__main__": + unittest.main()