Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do a Rust function and a FFI C++ function execute in reverse order?

Tags:

c++

rust

I tried to link an external C++ function with my Rust application. This function works but it does not execute in the same order as it is called from Rust code.

Why does this happen? Is this documented?

Here is a listing of the Rust application:

extern crate libc;
use libc::c_int;

#[link(name = "Project1", kind = "static")]
extern "C" {
    pub fn lib_fun(i: c_int) -> c_int;
}

fn main() {
    unsafe {
        lib_fun(2);
    }
    println!("from Rust: {}", 2);
}

"Project1" library looks like this:

#include <stdio.h>

extern "C" {
    int lib_fun(int t) {
        printf("from C++: %d\n", t);
        return t;
    }
}

Expected output:

from C++: 2
from Rust: 2

The real output is in the reverse order:

from Rust: 2
from C++: 2

Is the external function lib_func executed in another thread? Why?

Details:

  • Platform: Windows 7, x64,
  • Rust: 1.26.0 (nightly),
  • C++: Microsoft Visual Studio Community 2017 Preview 15.7.0 Preview 2.0
  • Terminal: IntelliJ IDEA's integrated terminal.
like image 457
Michail Avatar asked Mar 25 '18 11:03

Michail


1 Answers

External C++ code uses its own buffer to write to stdout and it is flushed to the system buffer later than the Rust caller does. printf("...\n") doesn't flush the stdout buffer as I expected.

Instead, I need to flush it manually, for example by calling fflush(stdout);

Thanks for this answer to @Veedrac

like image 76
Michail Avatar answered Oct 05 '22 03:10

Michail