-1

In my Rust code I have to use some C function in the Rust side. In that function I have to pass some structures as example.

#[repr(C)]
pub structA {
    pub buffer:[i8; 8000],
    pub writing: i32,
    pub written_num: i32,
    pub write_index: i32,
    pub id: i32,
    pub sortArray: StructB,
}

FFI calling part

let mut struc_a = Box::new(structA::new());
unsafe {
    ProcessStrucA(&mut *structA);
}

structure in C side

typedef struct {
    char buffer[8000];
    size_t writing;
    size_t written_num;
    size_t write_index;
    int id;
    StructB structB;
} structA;

When I'm passing above structure to C side it will not get the values which we send from the Rust side. According to my understanding this could be happening due to invalid memory handling. How do I resolve this issue?

RUC...
  • 133
  • 10
  • how is your structure declared on the C side? – Jean-François Fabre Jan 02 '23 at 13:55
  • 2
    It will likely be a problem that `structA` has not been declared as [`repr(C)`](https://doc.rust-lang.org/nomicon/other-reprs.html#reprc). The definition of `StructB` is also missing. – E_net4 Jan 02 '23 at 14:00
  • E_net4 the comment flagger it has been used in the rust side – RUC... Jan 02 '23 at 14:13
  • Please provide the complete definition of `ProcessStrucA`. Can you also expand what really happens to the struct value and what you expected the function to do? Can you also exclude mistakes from the C definition of this function? – E_net4 Jan 02 '23 at 14:18
  • Sorry updated the code in question could please check – RUC... Jan 02 '23 at 14:19
  • 3
    1. `i32` is not a correct translation from `size_t`. Use `usize` instead. https://stackoverflow.com/questions/32307004/what-is-the-rust-equivalent-of-size-t ; 2. `playerLiveIndex` is present in the C definition but not in the Rust struct. Perhaps you are better off using [rust-bindgen](https://rust-lang.github.io/rust-bindgen/) to generate the FFI interfaces. – E_net4 Jan 02 '23 at 14:23
  • Thank it has been work after change the pub buffer:[i8; 8000], as follows pub buffer:[::std::os::raw::c_char; 8000], – RUC... Jan 02 '23 at 16:30
  • I'd agree with @E_net4thecommentflagger, you should probably use bindgen to generate the bindings. – Finomnis Jan 02 '23 at 20:28

1 Answers1

-2

I have changed the buffer type ::std::os::raw::c_char then it works as expected. Thanks

RUC...
  • 133
  • 10
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 03 '23 at 02:20