Golang丰富的I/O 二----cgo版Hello World
Golang丰富的I/O 二----cgo版Hello World
在《Golang丰富的I/O----用N种Hello 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》

浙公网安备 33010602011771号