分享
  1. 首页
  2. 文章

GoLang之调用C接口的使用方法

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

2014年06月10日 wcdj


摘要:本文主要介绍在GoLang中如何实现调用C接口。由于Go的官网经常被墙,导致无法浏览官方的详细文档,偶然间在浏览GoLang的源码中找到了一些关于cgo的用法,具体路径在go/misc/cgo目录下。


例如,在go/misc/cgo/gmp/gmp.go文件中可以找到如何在GoLang中引用C Library的方法:

An example of wrapping a C library in Go. This is the GNU multiprecision library gmp's integer type mpz_t wrapped to look like the Go package big's integer type Int.


下面是一个简单的例子:hello.go

完整的代码可以浏览这里:https://github.com/gerryyang/goinaction/blob/master/src/cgo/src/hello.go

package main
/*
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "../inc/hello.h"
// intentionally write the same LDFLAGS differently
#cgo linux LDFLAGS: -L../lib -lhello
#cgo darwin LDFLAGS: -L../lib -lhello
#if 0
void hello(const char *name)
{
	printf("%s\n", name);
	return;
}
#endif
*/
import "C"
import (
	"fmt"
	"time"
)
func Hello(s string) {
	cs := C.CString(s)
	C.hello(cs)
}
func main() {
	Seed(1000)
	fmt.Println(int(C.random()))
	time.Sleep(time.Duration(1) * time.Second)
	fmt.Println(int(C.random()))
	fmt.Println("getpid:", int(C.getpid()))
	C.puts(C.CString("call C puts"))
	Hello("call C's go wrapper func")
	C.hello(C.CString("call C hello func"))
}
func Seed(i int) {
	C.srandom(C.uint(i))
}


参考

[1] http://www.cnblogs.com/yjf512/archive/2012/07/19/2599304.html

[2] http://tonybai.com/tag/cgo/





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

本文来自:CSDN博客

感谢作者:delphiwcdj

查看原文:GoLang之调用C接口的使用方法

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

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

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏