[Python] How to pass a byte buffer from python to C/C++

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am creating a library in C++ with Python bindings.

    The library takes buffer created in Python code and processes it in several ways. On my way to achieve that, I used the example below generated by Google's Gemini as starter for that part of the code. But I am getting an error:

    Here is the C++ code:

    #include <pybind11/pybind11.h>

    struct MyStruct {
    int value;
    double* data;
    int size;

    // Constructor
    MyStruct(int val, int sz) : value(val), size(sz) {
    data = new double[sz];
    for (int i = 0; i < sz; ++i) {
    data = 0.0; // Initialize data to 0
    }
    }

    // Destructor to free allocated memory
    ~MyStruct() {
    delete[] data;
    }
    };

    PYBIND11_MODULE(example, m) {
    pybind11::class_<MyStruct>(m, "MyStruct")
    .def(pybind11::init<int, int>())
    .def_readwrite("value", &MyStruct::value)
    .def_readwrite("data", &MyStruct::data)
    .def_readwrite("size", &MyStruct::size);
    }


    Here is the Python code:

    import example

    my_struct = example.MyStruct(10, 5)

    print(f"Value: {my_struct.value}")
    print(f"Size: {my_struct.size}")

    my_struct.value = 20
    print(f"Modified Value: {my_struct.value}")

    # Access and modify data through the pointer (be careful!)
    for i in range(my_struct.size):
    my_struct.data = i * 2.0

    print("Data:", [my_struct.data for i in range(my_struct.size)])


    And this is the error I am getting:

    Value: 10
    Size: 5
    Modified Value: 20
    Traceback (most recent call last):
    File "./test.py", line 13, in <module>
    my_struct.data = i * 2.0
    ~~~~~~~~~~~~~~^^^
    TypeError: 'float' object does not support item assignment


    So, how to fix this error. And my final goal is really to pass a byte buffer from python to C++ code, if there is any better way to do it, please let me know.

    Continue reading...

Compartilhe esta Página