How to get *mut libc::c_char in place of *mut libc::c_char pointer?


#1

I would like to write Rust ffi to C code like:

#define BUFSIZE_IN_PLACE_MAX 32
struct {
  int small_flag;
  int size;
  char *buf;
}

return small_flag ? (char *)&buf : buf;

When small_flag is true, char values are put in place of buf, not where buf points to.
For small_flag == true case, I have the constant value for the maximum length BUFSIZE_IN_PLACE_MAX.


#2

How do 32 chars fit in this struct?


#3

Sorry, I simplified the struct too much.
Actually more fields are there after buf and 32 chars fits in buf and those fields.


#4

This is pretty similar to C actually: you can transmute a pointer to a field to a pointer to any other type

let inplace_buf: &mut [c_char; 32] = transmute(&mut my_struct.buf);

Very unsafe and unrecommended :smile:

As a method on said struct that would check the flag, it could be made safe though.


#5

That worked!
Thanks!