Add optional support to C++ extensions (#7055)

This commit is contained in:
Peter Goldsborough
2018-04-28 01:59:50 +01:00
committed by GitHub
parent 7b09bc72a5
commit 2e023a29e4
3 changed files with 17 additions and 0 deletions

View File

@ -20,8 +20,16 @@ struct MatrixMultiplier {
at::Tensor tensor_;
};
bool function_taking_optional(at::optional<at::Tensor> tensor) {
return tensor.has_value();
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("sigmoid_add", &sigmoid_add, "sigmoid(x) + sigmoid(y)");
m.def(
"function_taking_optional",
&function_taking_optional,
"function_taking_optional");
py::class_<MatrixMultiplier>(m, "MatrixMultiplier")
.def(py::init<int, int>())
.def("forward", &MatrixMultiplier::forward)

View File

@ -100,6 +100,12 @@ class TestCppExtension(common.TestCase):
# 2 * sigmoid(0) = 2 * 0.5 = 1
self.assertEqual(z, torch.ones_like(z))
def test_optional(self):
has_value = cpp_extension.function_taking_optional(torch.ones(5))
self.assertTrue(has_value)
has_value = cpp_extension.function_taking_optional(None)
self.assertFalse(has_value)
if __name__ == '__main__':
common.run_tests()

View File

@ -57,4 +57,7 @@ public:
}
};
// http://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html#c-17-library-containers
template <typename T>
struct type_caster<at::optional<T>> : optional_caster<at::optional<T>> {};
}} // namespace pybind11::detail