Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. pub fn numpy_from_vec_u32(input: Vec<u32>) -> PyResult<PyObject> {
  2. let len = input.len();
  3.  
  4. //import numpy
  5. let gil = Python::acquire_gil();
  6. let py = gil.python();
  7. let locals = PyDict::new(py);
  8. locals.set_item("numpy", py.import("numpy")?)?;
  9.  
  10. //create the array
  11. let code = format!("numpy.zeros(({},), numpy.uint32)", len);
  12. let rr: PyObject = py.eval(&code, None, Some(&locals))?.extract()?;
  13. locals.set_item("arr", rr)?;
  14.  
  15. //figure out where the pointer is and turn it into pointer
  16. let code = "arr.ctypes.data";
  17. let ptr_py: PyObject = py.eval(code, None, Some(&locals))?.extract()?;
  18. let ptr_us: usize = ptr_py.extract(py)?;
  19. let ptr: *mut u32 = ptr_us as *mut u32; // why does this not need unsafe?
  20.  
  21. //write the data
  22. let da_array = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
  23. for i in 0..len {
  24. da_array[i] = input[i];
  25. }
  26. //return the python object
  27. let result: PyObject = py.eval("arr", None, Some(&locals))?.extract()?;
  28. Ok(result)
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement