Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda