what is c++
uint8_t *
uint64_t
in rust
what is c++
uint8_t *
uint64_t
in rust
uint8_t ,uint16_t , uint32_t and uint64_t . are equal respectively to: unsigned char , unsigned short ,unsigned int and unsigned long long .
Qn is not so clear,can you explain in more detail.
i want to translate rust point to ffi data with c.
such as the funtion in c
void call_c (int8_t *){};
at rust
struct TransData{
ptr: &[u8]
}
extern "c"{
fn call_c (mut *c_char)
}
i am not sure that the raw type in rust
Question: When calling call_c
, how will the C part know the size of the array?
You can get the raw pointer for the slice with as_ptr
:
fn my_func(data: &TransData) {
unsafe {
let ptr = data.ptr.as_ptr(); // note: i8_t is signed, while u8 isn't, consider casting, changing the signature type or structure type.
call_c(ptr);
}
}
The C type uint8_t *
is equivalent to the Rust type *mut u8
.
uint64_t
is equivalent to Rust's u64
.
If you want to have void call_c (int8_t *){};
, the rust binding would be:
extern "C" {
fn call_c(*mut i8);
}
If you have a void call_c (char *){};
, then you would write:
use std::os::raw::c_char;
extern "C" {
fn call_c(*mut c_char);
}
But if your function takes int8_t
, then you want to give it an i8
in Rust.
The biggest difference between C and Rust types is that in Rust, types are always nested outside->in and left->right. Things are also renamed, but that's a smaller change.
If you need a pointer to some type T
, the type is *mut T
. If you need an immutable pointer, the type is *const T
.
as you say
how can i initialize mut* u8
?
It depends on what you want it to be! Something similar to the last post here would likely work for *mut u8
: How to use void ** - #5 by mbrubeck.
If you want it to be a reference to a stack variable, you can simply do
let mut v: u8 = 0u8;
let ptr: *mut u8 = &mut v;
Note that the type is *mut u8
in Rust, not mut* u8
.
However, this might not be useful. Usually, the only reason you would use *mut u8
is if you want to interact with a C api. So that C api dictates what you need. If this is your situation, what api or library are you trying to use?
If you aren't trying to use a C library, then I recommend using Rust references rather than raw pointers. In Rust, this is the standard way: you don't use *mut
raw pointers unless you're talking to C
. This book chapter has a lot of details on references: References and Borrowing - The Rust Programming Language
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.