Skip to main content

02_copy/
02-copy.rs

1use cudarc::driver::{CudaContext, CudaSlice, DriverError};
2
3fn main() -> Result<(), DriverError> {
4    let ctx = CudaContext::new(0)?;
5    let stream = ctx.default_stream();
6
7    let a: CudaSlice<f64> = stream.alloc_zeros::<f64>(10)?;
8    let mut b = stream.alloc_zeros::<f64>(10)?;
9
10    // you can do device to device copies of course
11    stream.memcpy_dtod(&a, &mut b)?;
12
13    // but also host to device copys with already allocated buffers
14    stream.memcpy_htod(&vec![2.0; b.len()], &mut b)?;
15    // you can use any type of slice
16    stream.memcpy_htod(&[3.0; 10], &mut b)?;
17
18    // you can transfer back using clone_dtoh
19    let mut a_host: Vec<f64> = stream.clone_dtoh(&a)?;
20    assert_eq!(a_host, [0.0; 10]);
21
22    let b_host = stream.clone_dtoh(&b)?;
23    assert_eq!(b_host, [3.0; 10]);
24
25    // or transfer into a pre allocated slice
26    stream.memcpy_dtoh(&b, &mut a_host)?;
27    assert_eq!(a_host, b_host);
28
29    Ok(())
30}