pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

Help to implement an unified binding tool across languages

Open zdzhaoyong opened this issue 4 years ago • 1 comments

I was tring to write a binding tool for multiple languages. See: Svar, A Tiny Modern C++ Header Brings Unified Interface for Different Languages. Now it supports binding C++11 to Python and Node.JS at the same time (more languages will be supported). However, as I am not so familar to the Python low levels, the class binding is OK on both Linux and Macos, but on windows it leads to unkown segment fault. Would you please help me to find out why and fix it?

zdzhaoyong avatar Apr 19 '21 02:04 zdzhaoyong


#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <memory>
#include <iostream>

namespace py = pybind11;

class MyClass {
public:
    int value;
    
    MyClass(int v) : value(v) {}
    void display() {
        std::cout << "Value: " << value << std::endl;
    }
    void set_value(int v) {
        value = v;
    }
    int get_value() const {
        return value;
    }
};

// Function to create a MyClass object
std::shared_ptr<MyClass> create_myclass(int value) {
    return std::make_shared<MyClass>(value);
}

// Python bindings using pybind11
PYBIND11_MODULE(my_module, m) {
    py::class_<MyClass>(m, "MyClass")
        .def(py::init<int>())
        .def("display", &MyClass::display)
        .def("set_value", &MyClass::set_value)
        .def("get_value", &MyClass::get_value);

    m.def("create_myclass", &create_myclass, "Create an instance of MyClass");
}

ljluestc avatar Dec 24 '24 23:12 ljluestc