背景:
在golang中调用c函数时,会通过slice传递一组数;以及想通过二级指针引用获取c中的变量值,这样就不用再c中单独定义变量,有可能还有手动释放变量。
package main
/*
#include <stdio.h>
int loop(int** list_data, int leng, char** data)
{
int* m = (int*)list_data;
int sum = 0;
for(int i=0; i<leng; i++)
{
sum += m[i];
}
*data = "finised task";
return sum;
}
*/
import "C"
import (
"unsafe"
"fmt"
)
func main () {
var ids []int32 = []int32{1,2,3,5}
var res *C.char
leng := C.int(len(ids))
le := C.loop((**C.int)(unsafe.Pointer(&ids[0])),leng ,&res)
fmt.Println(le)
fmt.Println(C.GoString(res))
fmt.Println(ids)
}
unsafe.Pointer(&ids[0])(**C.int)(unsafe.Pointer(&ids[0]))&res