Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
What is the official Rust guidance for interoperability with C++, in particular passing and returning structs as arguments?

I'm trying to adapt some layers of existing C++ code to be used by Rust and apparently the way is through a C API.

For example, one function might return a struct as an object

#pragma pack(push,4)
struct Result {
    char ch;
    int32_t sum1;
    int32_t sum2;
};
#pragma pack(pop)

extern "C"
Result
muladd(int32_t a, int32_t b, int32_t c) {
    return Result{1, a+b*c, a*b+c};
}

And from Rust I'm doing

#[repr(C,align(4))]
pub struct Result {
    pub ch: i8,
    pub sum1: i32,
    pub sum2: i32,
}

extern "C" {
    pub fn muladd( a:i32, b:i32, c:i32 ) -> Result;
}

pub fn usemuladd( val: i32 ) -> i32 {
    unsafe {
       let res = muladd( val, val, val );
       return res.sum1;
    }
}

I'm seeing odd results with respect to alignment and packing of structures. I have read that Rust can play around with structs, and neither ordering or packing are guaranteed.

It seems that using #[repr(C)] and extern "C" is the key to a happy compatibility layer. My question is then: can I trust that these two will get me solid through or there will always be unannounced edge cases that I have to worry about?

https://godbolt.org/z/aEh4jKxxf

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

extern "C" on both sides + #[repr(C)] on the Rust side + only using C-compatible types for interfacing between C++ and Rust, should work.

Alternatively, see cxx and autocxx.

over 4 years ago · Santiago Trujillo Report

0

If you're looking to get a translation between the codes, you could use cbindgen and specify the output as C++ which is already default, or you could follow Solomon Ucko's suggestion.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!