pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

compare_buffer_info does not consider <i and i equal on a little-endian machine

Open eric-wieser opened this issue 6 years ago • 1 comments

The compare_buffer_info template will reject buffer formats of <i and i as being different.

This can be observed by calling bind_vector on vector<int32_t> with py::buffer_info(), then attempting to construct one as:

arr = (ctypes.c_int32 * 10)()
MyVector(arr)
# TypeError: TypeError: Format mismatch (Python: <i C++: i)

<i means "little endian int", and i means "native int". On a little-endian machine, these should be considered compatible.

eric-wieser avatar May 15 '19 10:05 eric-wieser


import ctypes
import pybind11 as py

# C++ code for defining the MyVector class
class MyVector:
    def __init__(self, arr):
        self.arr = arr
    
    def __repr__(self):
        return f"MyVector({self.arr})"
    
    # Overload the __buffer__ method to handle buffer information
    def __buffer__(self):
        return py.buffer_info(self.arr)

# Python code for using ctypes with pybind11
def test_vector_binding():
    # Create a ctypes array of 10 int32 elements
    arr = (ctypes.c_int32 * 10)()

    # Bind the ctypes array to MyVector
    vector_instance = MyVector(arr)

    # Display the vector instance
    print(vector_instance)

if __name__ == "__main__":
    test_vector_binding()

ljluestc avatar Nov 23 '24 18:11 ljluestc