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)
	
    C.free(unsafe.Pointer(cname))        /*C.CString存在内存泄露需要释放*/
	
}

执行

      go run test.go 

结果:

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

猜你喜欢

转载自blog.csdn.net/woailp___2005/article/details/105998128