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

majianguo · · 748 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:majianguo

查看原文:Golang丰富的I/O 二----cgo版Hello World

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

748 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传