pybind / pybind/pybind11

[QUESTION] Segfault when exposing class member variable with buffer protocol

Open
#2,985 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

I want to expose the following class, specifically I am interested in the *voxelBlocks:

template<class ITMVoxel>
    class ITMLocalVBA
    {
    private:
        ORUtils::MemoryBlock<TVoxel> *voxelBlocks;
        MemoryDeviceType memoryType;

    public:
        inline TVoxel *GetVoxelBlocks(void) { return voxelBlocks->GetData(memoryType); }
        inline const TVoxel *GetVoxelBlocks(void) const { return voxelBlocks->GetData(memoryType); }
        int lastFreeBlockId;
        int allocatedSize;
  }

GetData(MemoryDeviceType memoryType) looks like this:

/** Get the data pointer on CPU or GPU. */
inline DEVICEPTR(T)* GetData(MemoryDeviceType memoryType)
{
	switch (memoryType)
	{
	case MEMORYDEVICE_CPU: return data_cpu;
	case MEMORYDEVICE_CUDA: return data_cuda;
	}

	return 0;
}

Reading the documentation, it seems that the following buffer protocol should suffice:

  PYBIND11_NUMPY_DTYPE(ITMVoxel, sdf, w_depth);  // sdf, w_depth are uchar and short

  py::class_<ITMLocalVBA<ITMVoxel>>(m, "ITMLocalVBA_ITMVoxel", pybind11::buffer_protocol())
    .def_readonly("allocated_size", &ITMLocalVBA<ITMVoxel>::allocatedSize)
    .def_buffer([](ITMLocalVBA<ITMVoxel>& v) -> pybind11::buffer_info {
      return pybind11::buffer_info(
        v.GetVoxelBlocks(), 
        sizeof(ITMVoxel), 
        py::format_descriptor<ITMVoxel>::format(), 
        1, 
        { v.allocatedSize }, 
        { sizeof(ITMVoxel) }
      );
    })
  ;

However, when I try to access it, the program crashes (with a segmentation fault).
Does anyone have a clue? Help would be much appreciated, my Master thesis depends on it.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the shown ITMLocalVBA::GetVoxelBlocks method and the def_buffer lambda, then reproduce the buffer access while checking the returned pointer, format, shape, and lifetime. Done means the exposed buffer can be accessed without a segmentation fault and represents the intended voxel blocks; no repository file or test is named in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api, tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.