GO語言調用c動態庫

test.h如下:

#include<stdio.h>

int add(int a,int b,char *name,int *c);

test.c如下:

#include "test.h"

int add(int a,int b,char *name,int *c)
{
        printf("-----name[%s]\n",name);
        memcpy(name,"hello",5);
        *c = a+b;
        return a+b;
}

編譯動態庫

       gcc -w test.c -fPIC -shared -o libtest.so

 

test.go如下:

package main


/*
#cgo CFLAGS: -I./
#cgo LDFLAGS: -L./ -ltest
#include "test.h"
#include <stdlib.h>
*/
import "C"

import (
    "fmt"
)

func main(){

	name := "nxy"
	cname := C.CString(name)
	
	a := C.int(3)
	b := C.int(6)
	c := C.int(0)
	m := C.add(a,b,cname,&c)
	fmt.Println(m)
	fmt.Println(C.GoString(cname))
	fmt.Println(c)
	
	
}

執行

      go run test.go 

結果:

-----name[nxy]
9
hello
9

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章