go cgo

参考:https://golang.org/cmd/cgo/

     cgo 可以在go中调用c语言的函数,实例如下,实例代码见 https://github.com/robertzhai/go/tree/master/go_programming_study/src/cgo

1. cprint.go

package main

/*
#include <stdio.h> 
#include <stdlib.h>
*/
import "C"
import (
   "unsafe"
)

func main() {
   cstr := C.CString("Hello cgo")
   C.puts(cstr)
   C.free(unsafe.Pointer(cstr))
}

import "C" 是导入cgo的包,前面的注释是对应的c代码和include指令,需要注释

2.cfunc.go,调用c自定义函数
package main
/*
#include <stdio.h>
#include <stdlib.h>
void output(char *str) {
    printf("%s\n", str);
}
*/
import "C" //此处和上面的C代码一定不能有空行 否则会报错
import "unsafe"
func main() {
   str := "hello cgo"
   //change to char*
   cstr := C.CString(str)
   C.output(cstr)
   C.free(unsafe.Pointer(cstr))
}

3. cpointer.go  函数指针操作
package main

import "fmt"

/*
#include<math.h>
typedef int (*intFunc) ();

 int proxy_int_func(intFunc f)
 {
      return f();
 }

 int userfunc()
 {
       return 1;
 }
 */
import "C"

func main() {
   f := C.intFunc(C.userfunc)
   fmt.Println(int(C.proxy_int_func(f)))
   var n = C.sqrt(1)
   fmt.Print(n)
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值