Go - 访问C动态分配数组
使用 unsafe 结合类型转换 *(*[6]C.type) 可将C动态分配数组转换为go识别固定数组类型.
示例
*(*[6]C.uint64_t)(unsafe.Pointer(ptr)) 转换指针ptr 为固定数组类型:
package main
/*
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
void* alloc_int(void)
{
uint64_t *p = (void *)malloc(sizeof(uint64_t) * 6);
for (int i = 0; i < 6; i ++) {
p[i] = i + 60;
}
return (void *)p;
}
*/
import "C"
import (
"unsafe"
"fmt"
)
func main() {
ptr := C.alloc_int()
v := *(*[6]C.uint64_t)(unsafe.Pointer(ptr))
for _, a := range v {
fmt.Printf("%v\n", a)
}
fmt.Printf("len: %v\n", len(v));
fmt.Printf("0: %v\n", uint64(v[0]));
}
go build carray.go 输出结果:
# ./carray
60
61
62
63
64
65
len: 6
0: 60
该博客介绍了如何在Go语言中使用unsafe包和类型转换来访问C动态分配的数组。通过示例展示了从C的void指针转换为Go中的固定大小数组的过程,并展示了遍历和打印数组元素的代码。此外,还展示了输出数组长度及特定元素值的方法。
1168

被折叠的 条评论
为什么被折叠?



