簡體   English   中英

為什么在C循環中使用printf的Rust代碼不能顯示輸出,而在C ++循環中使用std :: cout可以顯示輸出呢?

[英]Why does Rust code using printf in a loop from C not display output, but using std::cout in a loop from C++ does?

我使用Rust用循環( forwhile )調用C函數,該循環使用printf函數顯示內容,但是C函數不顯示printf任何輸出。

C代碼:

#include <stdio.h>
#include <unistd.h>

void print_c() {
  int s = 3;
  while (1) {
    printf("%d\n", s);
    sleep(1);
  }
}

但是,使用C ++時,會成功生成輸出。

C ++代碼:

#include <iostream>
#include <stdint.h>
#include <unistd.h>

extern "C" {
  int print_it(int32_t num) {
    while (1) {
        std::cout << num << std::endl;
        sleep(1);
    }
  }
}

C被打包為一個名為“ cthread”的共享庫。 C ++名為“ cppthread”。

這是Rust調用的C庫:

#[link(name = "cthread")]
extern "C" {
    fn print_c();
}

fn main() {
    unsafe { print_c() };
}

Rust調用了C ++庫:

#[link(name = "cppthread")]
extern "C" {
    fn print_it();
}

fn main() {
    unsafe { print_it() };
}

我嘗試了您的C版本,它在macOS中對我有用。 由於您沒有告訴我們您的操作系統,因此很難知道它是否特定於平台。 嘗試在printf之后添加一個fflush(stdout)

#include <stdio.h>
#include <unistd.h>

void print_c() {
  int s = 3;
  while (1) {
    printf("%d\n", s);
    fflush(stdout); // This makes sure stdout is not being buffered.
    sleep(1);
  }
}

至於您的C ++版本,它在Rust代碼中有其自身的問題。

由於您的C ++版本返回一個int,並將int作為參數。 您需要定義extern定義才能顯示出來。 由於您實際上使用了int32_t ,因此我將i32用於該類型。 但是,您返回一個int (注意:您實際上未在代碼中返回任何內容)。 ,並且由於int的大小在不同平台上可能不同,因此最好使用libc::c_int

extern crate libc;
use libc::c_int;

#[link(name = "cppthread")]
extern {
    fn print_c(num: i32) -> c_int;
}

fn main() {
    unsafe { print_c(10) };
}

您的C和C ++版本不相同。

您的C版本僅打印數字和換行符。 它不進行顯式刷新(然后由I / O堆棧的各個層決定何時執行-幾乎可以肯定的是,考慮到sleep(1) ,這將需要一些時間!)。

您的C ++版本會打印一個數字,然后(通過endl )都打印一個換行符並刷新。 這就是為什么您總是立即看到結果的原因。

os << endlos << '\\n' << flush

使用fflush ,使您的C版本也可以輕松做到這一點:

#include <stdio.h>
#include <unistd.h>

void print_c() {
  int s = 3;
  while (1) {
    printf("%d\n", s);
    fflush(STDOUT);
    sleep(1);
  }
}

這個問題與Rust無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM