Skip to content

Commit 35a2a6d

Browse files
feat(mwrap): add mcpplibs.mwrap.nanobind 3.1.0 (#972)
1 parent 0df099c commit 35a2a6d

7 files changed

Lines changed: 231 additions & 0 deletions

File tree

‎mcpp.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ members = [
2121
"tests/mwrap/lua-embed",
2222
"tests/mwrap/quickjs-embed",
2323
"tests/mwrap/pocketpy-embed",
24+
"tests/mwrap/nanobind-embed",
2425
"tests/mwrap/libpng-image",
2526
"tests/mwrap/libwebp-image",
2627
"tests/mwrap/slint-ui",

‎pkgs/mwrap/nanobind.lua‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
-- Immutable upstream-aligned mwrap source release (nanobind-m mwrap-3.1.0).
2+
-- The CN mirror is added by a maintainer with mcpp-res access; until then CN
3+
-- users fall back to the GitHub release (docs/cn-mirror.md).
4+
package = {
5+
spec = "1",
6+
namespace = "mcpplibs.mwrap",
7+
name = "nanobind",
8+
description = "nanobind-m: nanobind 3.1.0 (C++/Python bindings, STL casters, ndarray/DLPack, operators) as C++23 modules",
9+
licenses = { "Apache-2.0" },
10+
repo = "https://github.com/mcpplibs/nanobind-m",
11+
type = "package",
12+
extensions = {
13+
autoupdate = {
14+
tag = "mwrap-${version}",
15+
url = "https://github.com/mcpplibs/nanobind-m/releases/download/${tag}/nanobind-m-${version}.tar.gz",
16+
},
17+
},
18+
xpm = {
19+
linux = {
20+
["3.1.0"] = {
21+
url = "https://github.com/mcpplibs/nanobind-m/releases/download/mwrap-3.1.0/nanobind-m-3.1.0.tar.gz",
22+
sha256 = "38d68f89744ce241197133a4cc07330e5e344e752d1b8a98826f140e8a05ef39",
23+
},
24+
},
25+
macosx = {
26+
["3.1.0"] = {
27+
url = "https://github.com/mcpplibs/nanobind-m/releases/download/mwrap-3.1.0/nanobind-m-3.1.0.tar.gz",
28+
sha256 = "38d68f89744ce241197133a4cc07330e5e344e752d1b8a98826f140e8a05ef39",
29+
},
30+
},
31+
windows = {
32+
["3.1.0"] = {
33+
url = "https://github.com/mcpplibs/nanobind-m/releases/download/mwrap-3.1.0/nanobind-m-3.1.0.tar.gz",
34+
sha256 = "38d68f89744ce241197133a4cc07330e5e344e752d1b8a98826f140e8a05ef39",
35+
},
36+
},
37+
},
38+
}

‎tests/mwrap/check_installed_template.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
"mcpplibs.mwrap.slint": ("slint.cppm", "upstream/slint/LICENSE.md", b"Slint License", b"SixtyFPS"),
3636
"mcpplibs.mwrap.wuffs": ("wuffs.cppm", "upstream/wuffs/LICENSE", b"Apache License", b"The Wuffs Authors"),
3737
"mcpplibs.mwrap.protobuf": ("protobuf.cppm", "upstream/protobuf/LICENSE", b"Redistribution and use in source and binary forms", b"Google"),
38+
"mcpplibs.mwrap.nanobind": ("nanobind.cppm", "upstream/nanobind/LICENSE", b"Wenzel Jakob", b"Wenzel Jakob"),
3839
}
3940

4041

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Point the consumer at the declared xim:python SDK: its headers, its link
2+
// library and, for the embedded interpreter, the home passed to PyConfig.
3+
import std;
4+
import mcpp;
5+
6+
namespace {
7+
8+
namespace fs = std::filesystem;
9+
10+
bool has_python_h(const fs::path& dir) {
11+
std::error_code ec;
12+
return fs::is_regular_file(dir / "Python.h", ec);
13+
}
14+
15+
} // namespace
16+
17+
int main() {
18+
const fs::path python = mcpp::xpkg_dir("xim", "python");
19+
if (python.empty() || !fs::is_directory(python)) {
20+
std::println(std::cerr, "nanobind-embed: the declared xim:python SDK is unavailable");
21+
return 1;
22+
}
23+
const bool windows = std::string_view(mcpp::target_os()) == "windows";
24+
const fs::path headers = windows ? python / "include" : python / "include" / "python3.13";
25+
const fs::path libraries = windows ? python / "libs" : python / "lib";
26+
if (!has_python_h(headers)) {
27+
std::println(std::cerr, "nanobind-embed: no Python.h under {}", headers.string());
28+
return 1;
29+
}
30+
if (!fs::is_directory(libraries)) {
31+
std::println(std::cerr, "nanobind-embed: no Python library directory at {}", libraries.string());
32+
return 1;
33+
}
34+
35+
mcpp::include_dir(headers.string().c_str());
36+
mcpp::link_search(libraries.string().c_str());
37+
mcpp::link_lib(windows ? "python313" : "python3.13");
38+
mcpp::runtime_search_dir((windows ? python : libraries).string().c_str());
39+
40+
const fs::path config_dir = fs::path(mcpp::out_dir()) / "python-sdk";
41+
std::error_code ec;
42+
fs::create_directories(config_dir, ec);
43+
std::ofstream config(config_dir / "python_sdk.h", std::ios::binary | std::ios::trunc);
44+
config << "#define MCPP_PYTHON_HOME R\"SDK(" << python.generic_string() << ")SDK\"\n";
45+
config.close();
46+
if (!config) {
47+
std::println(std::cerr, "nanobind-embed: cannot write python_sdk.h");
48+
return 1;
49+
}
50+
mcpp::include_dir(config_dir.string().c_str());
51+
mcpp::rerun_if_changed("build.mcpp");
52+
return 0;
53+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[package]
2+
name = "nanobind-embed"
3+
version = "3.1.0"
4+
description = "Consume the immutable nanobind wrapper: embedded CPython module with NB_MODULE, STL casters, classes, exceptions, ndarray and version constants"
5+
6+
[dependencies]
7+
mcpplibs.mwrap.nanobind = "3.1.0"
8+
9+
[dev-dependencies]
10+
mcpplibs.mtest = "0.11.3"
11+
12+
[xlings.workspace]
13+
"xim:python" = "3.13.12"
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
#include <mwrap/nanobind/macros.hpp>
2+
#include <python_sdk.h>
3+
4+
import std;
5+
import mcpplibs.mtest;
6+
import mcpplibs.mwrap.nanobind;
7+
import mcpplibs.mwrap.nanobind.stl;
8+
import mcpplibs.mwrap.nanobind.ndarray;
9+
10+
using namespace mcpplibs::mtest;
11+
namespace nb = nanobind;
12+
13+
namespace {
14+
15+
struct Point {
16+
double x = 0, y = 0;
17+
double norm() const { return std::sqrt(x * x + y * y); }
18+
};
19+
20+
std::string join_words(const std::vector<std::string>& words) {
21+
std::string result;
22+
for (const std::string& word : words) {
23+
if (!result.empty()) result += ' ';
24+
result += word;
25+
}
26+
return result;
27+
}
28+
29+
void fail_negative(int value) {
30+
if (value < 0) throw nb::value_error("negative value");
31+
}
32+
33+
} // namespace
34+
35+
NB_MODULE(nanobind_embed, m) {
36+
m.doc() = "nanobind-embed: the immutable nanobind wrapper";
37+
m.def("add", [](int a, int b) { return a + b; }, nb::arg("a"), nb::arg("b"));
38+
m.def("join_words", &join_words, nb::arg("words"));
39+
m.def("fail_negative", &fail_negative, nb::arg("value"));
40+
m.def("array_sum", [](nb::ndarray<const float, nb::ndim<1>> values) {
41+
double total = 0;
42+
for (std::size_t i = 0; i < values.shape(0); ++i) total += values(i);
43+
return total;
44+
}, nb::arg("values"));
45+
nb::class_<Point>(m, "Point")
46+
.def(nb::init<double, double>(), nb::arg("x") = 0, nb::arg("y") = 0)
47+
.def_rw("x", &Point::x)
48+
.def_rw("y", &Point::y)
49+
.def("norm", &Point::norm);
50+
}
51+
52+
UTest behavior{"behavior", [] {
53+
expect(fatal(PyImport_AppendInittab("nanobind_embed", PyInit_nanobind_embed) == 0))
54+
<< "PyImport_AppendInittab failed";
55+
56+
PyConfig config;
57+
PyConfig_InitPythonConfig(&config);
58+
PyStatus status = PyConfig_SetBytesString(&config, &config.home, MCPP_PYTHON_HOME);
59+
if (!PyStatus_Exception(status)) {
60+
config.parse_argv = 0;
61+
config.install_signal_handlers = 0;
62+
status = Py_InitializeFromConfig(&config);
63+
}
64+
PyConfig_Clear(&config);
65+
expect(fatal(!PyStatus_Exception(status))) << (status.err_msg ? status.err_msg : "unknown PyStatus");
66+
67+
struct Guard {
68+
~Guard() {
69+
if (Py_IsInitialized()) Py_Finalize();
70+
}
71+
} guard;
72+
73+
"module, functions and stl casters"_test = [] {
74+
expect(eq(PyRun_SimpleString(
75+
"import nanobind_embed as b\n"
76+
"assert b.add(2, 3) == 5\n"
77+
"assert b.add(a=10, b=32) == 42\n"
78+
"assert b.join_words(['hello', 'nanobind', 'world']) == 'hello nanobind world'\n"),
79+
0));
80+
};
81+
82+
"classes and exceptions"_test = [] {
83+
expect(eq(PyRun_SimpleString(
84+
"import nanobind_embed as b\n"
85+
"p = b.Point(3, 4)\n"
86+
"assert p.x == 3 and p.y == 4\n"
87+
"assert abs(p.norm() - 5.0) < 1e-12\n"
88+
"p.x = 6\n"
89+
"assert p.x == 6\n"
90+
"try:\n"
91+
" b.fail_negative(-1)\n"
92+
"except ValueError as error:\n"
93+
" assert str(error) == 'negative value'\n"
94+
"else:\n"
95+
" raise AssertionError('expected ValueError')\n"
96+
"b.fail_negative(1)\n"),
97+
0));
98+
};
99+
100+
"ndarray through the buffer protocol"_test = [] {
101+
expect(eq(PyRun_SimpleString(
102+
"import array\n"
103+
"import nanobind_embed as b\n"
104+
"values = array.array('f', [1.0, 2.0, 3.0])\n"
105+
"assert abs(b.array_sum(values) - 6.0) < 1e-12\n"),
106+
0));
107+
};
108+
}};
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import mcpplibs.mtest;
2+
import mcpplibs.mwrap.nanobind.macros;
3+
4+
using namespace mcpplibs::mtest;
5+
namespace macros = mcpplibs::mwrap::nanobind::macros;
6+
7+
static_assert(macros::NB_VERSION_MAJOR == 3);
8+
static_assert(macros::NB_VERSION_MINOR == 1);
9+
static_assert(macros::NB_VERSION_PATCH == 0);
10+
static_assert(macros::NB_VERSION_DEV == 0);
11+
12+
UTest versions{"versions", [] {
13+
expect(eq(macros::NB_VERSION_MAJOR, 3));
14+
expect(eq(macros::NB_VERSION_MINOR, 1));
15+
expect(eq(macros::NB_VERSION_PATCH, 0));
16+
expect(eq(macros::NB_VERSION_DEV, 0));
17+
}};

0 commit comments

Comments
 (0)