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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With