Replies: 1 comment
-
This is all described in the documentation. Please read it. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I am trying to understand how to use nanobind and how data ownership works.
And I have this very simple example:
my_ext.h
template <class T, int d> class Example { private: int integer; public: Example() { integer = 100; } int& getInteger(); void printClassInfo(); ~Example() {} };
my_ext.cpp
#include <nanobind/nanobind.h> #include "my_ext.h" namespace nb = nanobind; int add(int a, int b) { Example<double, 2> ex1; auto ex1b = ex1.getInteger(); ex1b = (double)a; Example<double, 2> ex2; auto ex2b = ex2.getInteger(); ex2b = (double)b; return ex1b + ex2b; } template<class T, int d> int& Example<T, d>:: getInteger() { return integer; } template<class T, int d> void Example<T, d>:: printClassInfo() { printf("Integer = %d\n", integer); } NB_MODULE(my_ext, m) { m.def("add", &add); nb::class_<Example<double, 3>>(m, "Double3Example") .def(nb::init<>()) .def("getInteger", &Example<double, 3>::getInteger, nb::rv_policy::reference_internal) .def("printClassInfo", &Example<double, 3>::printClassInfo); }
my_ext.py
from build import my_ext as example print("Create an instance of Example class") e = example.Double3Example() print("Print current class info") e.printClassInfo() print("Get the reference to a member variable") x = e.getInteger() old_x = x x = 200 print("Change value from {} to {}".format(old_x, x)) print("Print current class info") e.printClassInfo()
The output I get is
Create an instance of Example class Print current class info Integer = 100 Get the reference to a member variable Change value from 100 to 200 Print current class info Integer = 100
But shouldn't the value of integer be changed to 200? Very grateful if anyone can tell me where I am going wrong.
I apologize for the formatting issues with the code pasted above.
Beta Was this translation helpful? Give feedback.
All reactions