PyO3 / PyO3/rust-numpy

Recommended way for creating a wrapper class in Rust

Open
#426 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

question
Dominant language
Rust
Stars
1.4k
Forks
141
Avg merge
16m
Merged PRs (30d)
3

Description

Hey, I want to write some Rust algorithms that operate on a numpy array that was created in python. E.g.:

arr = np.ones((1000, 768))
dataset = MyRustWrapper(arr) # Rust wrapper class
idx = 199
dataset.get_nearest_neighbor(idx)

Because the array is quite big, I would like to avoid copying the data and just wrap a Array2<f32> that is passed from python.
But how can I take a Array2<f32> and pass it into the fn new of the Rust struct? I only managed to get this working, by extenting the lifetime of new<'py>(arr: PyReadonlyArray2<'py, f32>) -> PyResult<Self> to 'static with unsafe which is likely incorrect:

struct MyRustWrapper(PyReadonlyArray2<'static, f32>)
impl MyRustWrapper {
    fn new<'py>(arr: PyReadonlyArray2<'py, f32>) -> PyResult<Self>{
         Self(unsafe { std::mem::transmute(arr) })
    }
}

Also on a sidenote, how can I make sure that the rows of the numpy array are all f32 and are laid out as slices in memory?

Thanks in advance for any help.

Contributor guide

No contributing guide indexed for this repository

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 by reading the PyReadonlyArray2 APIs and the Rust wrapper constructor shown in the issue, focusing on ownership and lifetime requirements. Done should be a documented safe approach for wrapping the Python NumPy array without copying, including how to handle f32 dtype and row layout.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python, rust
Domain
api, data
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.