Rust and lack of header files

⚓ Rust    📅 2025-07-22    👤 surdeus    👁️ 2      

surdeus

So I am learning rust and need to mix both C and RUST.

The steps I am trying to do are as follows:

STEP 1: I have a C structure - defined in the C language header file, this MUST remain in C for practical reasons, a representative structure is:

   // Structure defined in a C header file.
   struct  FOOBAR {
          int member1;
          int member2;
          // Real struct has probably 20 to 30 elements
    };

    int  rust_calls_this_function( struct foobar *pFOOBAR );

    int c_calls_this_rust_function( struct foobar *pFOOBAR );

Step 2 - I run "bindgen cli" to create this using a Makefile (using build.rs is not practical for this situation - mostly chicken and egg issues)

Effectively - this creates a "foobar.rs" file based on the C header file.

Step 3 - I also have C functions I need to call from RUST, so I need to use CBINDGEN to produce the Header file for the rust functions C will call.

Step 4 - This effectively means I have three copies or definitions of the "struct foobar" - COPY (1) in the original H file, Copy (2) in the generated foobar.rs file, and I guess I need yet another copy (3) in the rust code that calls the C functions.

This seems very wrong to me an I think I am doing something wrong.

Related: How does one provide the implementation of a RUST function in a sperate file? Example: "bindgen" produces a RS file from a C header, it effectively has function definitions akin to a C header file.

However - If I modify that generated RS file by adding the implementation for these functions they will be over written then next time they are re-generated.

So It would seem that I should put the IMPLIMENTATION in some separate file and sort of "include" the other generated file - but rust does not have the concept of an include file like C has. Thus I am confused.

So my question is: What is the best practice when faced with using a structure (and function signatures) that where/when the user requires bi-directional interaction with RUST and C.

4 posts - 3 participants

Read full topic

🏷️ Rust_feed