dsz7121 2018-07-18 06:28
浏览 99
已采纳

无法打印到标准输出

I'm able to get the program here to print 42 as expected.

But I am unable to get the following program to print to stdout:

package main

// #include <stdlib.h>
// #include <stdio.h>
import "C"

import (
    "unsafe"
)

func main() {
    cs := C.CString("hello")
    defer C.free(unsafe.Pointer(cs))
    C.fputs(cs, (*C.FILE)(C.stdout))
}

It runs without error, but it doesn't print anything. The above snippet is mostly based off the "Strings and things" code here.

  • 写回答

2条回答 默认 最新

  • douci4026 2018-07-18 06:56
    关注

    Try this:

    package main
    
    // #include <stdlib.h>
    // #include <stdio.h>
    import "C"
    import "unsafe"
    
    func main() {
        cs := C.CString("hello")
        defer C.free(unsafe.Pointer(cs))
        C.puts(cs)
    }
    

    Explanation:

    The fputs method writes a string to a data stream, in your case stdout, which is directed towards a pointer to a file that doesn't exist because it has neither been opened nor defined anywhere previously. So even though the program appears to execute without error, you aren't seeing any of the stdout because it is being redirected to a nonexistent file.

    Further, it should be noted that simply dropping the code from the Strings and things section into a main program without some customization would not work because it is provided in the blog as a package, which is why there was confusion about the file existing. It seems that the print package from the blog post simply assumes the file you are attempting to write the data stream to has already been defined somewhere previously. It's a little confusing and they should probably adjust that.

    I replaced fputs with puts as well as removed the pointer to the file and the program executes just fine.

    Hope that even with the modifications this helps accomplish what you are looking for!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow
  • ¥15 densenet网络结构中,特征以cat方式复用后是怎么进行误差回传的
  • ¥15 STM32G471芯片spi设置了8位,总是发送16位
  • ¥15 R语言并行计算beta-NTI中tree文件的类型
  • ¥15 如何解读marsbar导出的ROI数据?
  • ¥20 求友友协助弄一下基于STC89C52单片机的声光控制灯原理图
  • ¥15 arduino双向交通灯设计
  • ¥15 有没有会粒子群算法的大能(○゜ε^○)求带不会出收敛图😭