I'm converting code from C to Rust
C code:
uint16_t W25Q64_read(uint32_t addr,uint8_t *buf,uint16_t n){ unsigned char *data; int rc; data = (unsigned char*)malloc(n+4); data[0] = CMD_READ_DATA; data[1] = (addr>>16) & 0xFF; // A23-A16 data[2] = (addr>>8) & 0xFF; // A15-A08 data[3] = addr & 0xFF; // A07-A00 rc = wiringPiSPIDataRW (_spich,data,n+4); memcpy(buf,&data[4],n); free(data); return rc-4; } Rust code:
pub fn read(&self, address: u32, number_of_bytes: u16) -> Result<Vec<u8>, u16> { let s: usize = number_of_bytes as usize + 4; let mut data = vec![0u8;s]; data[0] = CMD_READ_UNIQUE_ID; data[1] = (address>>16 & 0xFF) as u8; // A23-A16 data[2] = (address>>8 & 0xFF) as u8; // A15-A08 data[3] = (address & 0xFF) as u8; // A07-A00 let mut _r: i32 = 0; _r = unsafe{wiringPiSPIDataRW(self.spi_channel,data.as_mut_slice().as_mut_ptr(), data.len() as i32)}; let v = (&(data.as_slice())[4..]).to_vec(); Ok(v) } On the C code, I get 256 255 results when I try to read 256 bytes. On the Rust code, for the same address and same number of bytes, I get
0,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37,46,210,104,44,22,219,93,37 I always get this, I don't know why.
My assumption is that something is wrong with using a pointer to a slice owned by a vector. Somehow when C code tries to write to this slice, things go wrong. Could this possibly be the problem?
I cannot see anything wrong except for this.
https://stackoverflow.com/questions/66728200/using-pointer-to-slice-from-vec-when-calling-c-code-from-rust March 21, 2021 at 10:06AM
没有评论:
发表评论