zoukankan      html  css  js  c++  java
  • Golang丰富的I/O 二----cgo版Hello World

    Golang丰富的I/O ----cgoHello World

    Golang丰富的I/O----NHello World展示》中用多种Hello World的写法展示了golang丰富强大的I/O功能,在此补充一种cgo版的Hello World。以下代码源自go源码:


    main.go

    package main
    
    
    import"stdio"
    
    
    func main() {
    
        stdio.Stdout.WriteString(stdio.Greeting + "
    ")
    
    }
    

      

    file.go

    // skip
    
    
    // Copyright 2009 The Go Authors. All rights reserved.
    
    // Use of this source code is governed by a BSD-style
    
    // license that can be found in the LICENSE file.
    
    
    /*
    
    A trivial example of wrapping a C library in Go.
    
    For a more complex example and explanation,
    
    see ../gmp/gmp.go.
    
    */
    
    
    
    package stdio
    
    
    /*
    
    #include <stdio.h>
    
    #include <stdlib.h>
    
    #include <sys/stat.h>
    
    #include <errno.h>
    
    
    char* greeting = "hello, world";
    
    */
    
    import"C"
    
    import"unsafe"
    
    
    typeFile C.FILE
    
    
    // Test reference to library symbol.
    
    // Stdout and stderr are too special to be a reliable test.
    
    //var = C.environ
    
    
    func (f *File) WriteString(s string) {
    
        p := C.CString(s)
    
        C.fputs(p, (*C.FILE)(f))
    
        C.free(unsafe.Pointer(p))
    
        f.Flush()
    
    }
    
    
    func (f *File) Flush() {
    
        C.fflush((*C.FILE)(f))
    
    }
    
    
    var Greeting = C.GoString(C.greeting)
    
    var Gbytes = C.GoBytes(unsafe.Pointer(C.greeting), C.int(len(Greeting)))
    

      

    stdio.go

    // skip
    
    
    // Copyright 2009 The Go Authors. All rights reserved.
    
    // Use of this source code is governed by a BSD-style
    
    // license that can be found in the LICENSE file.
    
    
    package stdio
    
    
    /*
    
    #include <stdio.h>
    
    
    // on mingw, stderr and stdout are defined as &_iob[FILENO]
    
    // on netbsd, they are defined as &__sF[FILENO]
    
    // and cgo doesn't recognize them, so write a function to get them,
    
    // instead of depending on internals of libc implementation.
    
    FILE *getStdout(void) { return stdout; }
    
    FILE *getStderr(void) { return stderr; }
    
    */
    
    import"C"
    
    
    var Stdout = (*File)(C.getStdout())
    
    var Stderr = (*File)(C.getStderr())
    

      

    Go程序可以通过cgo工具非常方便地调用c函数。关于go调用C/C++或者C/C++调用go程序可以参考之前的系列随笔C/C++调用golang和《calling c++ from golang with swig---windows dll

  • 相关阅读:
    微信支付-微信公众号支付,微信H5支付,微信APP支付,微信扫码支付
    微信公众号支付开发当前URL未注册解决办法
    程序员头像
    jQuery简单实现iframe的高度根据页面内容自适应的方法(转)
    MySQL大表优化方案 Mysql的row_format(fixed与dynamic)
    PHP 测试杂项
    【转】MySQL的学习--触发器
    MYSQL PROCEDURE 测试用例
    CSS好看的按钮
    表格可在线编辑效果
  • 原文地址:https://www.cnblogs.com/majianguo/p/7921453.html
Copyright © 2011-2022 走看看