1. 程式人生 > >Golang豐富的I/O 二----cgo版Hello World

Golang豐富的I/O 二----cgo版Hello World

left dir 關於 blank more oid class bytes his

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 + "\n")

}

  

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

Golang豐富的I/O 二----cgo版Hello World