Go language calls c dynamic library

test.h is as follows:

#include<stdio.h>

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

test.c is as follows:

#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;
}

Compile dynamic library

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

 

test.go is as follows:

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存在内存泄露需要释放*/
	
}

carried out

      go run test.go 

result:

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

 

Guess you like

Origin blog.csdn.net/woailp___2005/article/details/105998128