Lagrange
Loading...
Searching...
No Matches
StubType.h
1/*
2 * Copyright 2025 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12#pragma once
13
14#include <nanobind/nanobind.h>
15
16namespace lagrange::python {
17
18// Wraps a C++ type `T` but renders as `Hint::value` in generated stubs. Use this
19// when nanobind's auto-generated stub for `T` is narrower than what the binding
20// actually accepts/returns (e.g. an Eigen vector that also takes a numpy array).
21// Conversion is delegated to `T`'s own caster, so runtime behavior is unchanged.
22//
23// `Hint` is a tag type with a `static constexpr char value[]`; declare reusable
24// hints with the LA_STUB_HINT macro below.
25//
26// Related nanobind issues:
27// https://github.com/wjakob/nanobind/issues/1155
28// https://github.com/wjakob/nanobind/issues/494
29// https://github.com/wjakob/nanobind/discussions/1243
30template <typename T, typename Hint>
32{
33 T value;
34};
35
36// Declares a stub-hint tag named `name` rendering as the type string `str`.
37#define LA_STUB_HINT(name, str) \
38 struct name \
39 { \
40 static constexpr char value[] = str; \
41 }
42
43// Common hint: accepts any array-like (list, tuple, numpy array, ...).
44LA_STUB_HINT(ArrayLikeHint, "numpy.typing.ArrayLike");
45
46} // namespace lagrange::python
47
48namespace nanobind::detail {
49
50template <typename T, typename Hint>
51struct type_caster<lagrange::python::StubType<T, Hint>>
52{
54 using TCaster = make_caster<T>;
55
56 NB_TYPE_CASTER(Wrapper, const_name(Hint::value))
57
58 bool from_python(handle src, uint8_t flags, cleanup_list* cleanup) noexcept
59 {
60 TCaster caster;
61 if (!caster.from_python(src, flags, cleanup)) return false;
62 value.value = caster.operator cast_t<T>();
63 return true;
64 }
65
66 static handle from_cpp(const Wrapper& w, rv_policy policy, cleanup_list* cleanup) noexcept
67 {
68 return TCaster::from_cpp(w.value, policy, cleanup);
69 }
70};
71
72} // namespace nanobind::detail
Main namespace for Lagrange.
Definition StubType.h:32