英文:
How can I pass Go arrays to C?
问题
我正在努力解决OpenGL ES的问题,但它没有正常工作。
然后我在C语言中成功实现了类似的功能。(我只是复制了Go代码,并对其进行了修改(语法),并删除了一些不重要的函数调用。)
我最终发现Go数组没有传递给C函数。(因此,作为顶点数组和索引的数组无法正确传递,并且在渲染时出现了错误。)
我使用以下代码进行了测试:
C函数部分:
void passTest(void *Ptr){
int *test = (GLfloat *)Ptr;
printf("C: test=%p\n", test);
printf("C: test[0]=%d\ntest[1]=%d\ntest[2]=%d\ntest[3]=%d\n", test[0], test[1], test[2], test[3]);
}
这是Go部分:
test := []int{ 0, 3, 9, 81018 }
var ptr unsafe.Pointer = (unsafe.Pointer)(&test)
fmt.Printf("Go: test=%p\n", ptr)
fmt.Printf("Go: test[0]=%d\ntest[1]=%d\ntest[2]=%d\ntest[3]=%d\n", test[0], test[1], test[2], test[3])
C.passTest(ptr)
结果是:
Go: test=0x10300010
Go: test[0]=0
test[1]=3
test[2]=9
test[3]=81018
C: test=0x10300010
C: test[0]=271581216
test[1]=4
test[2]=4
test[3]=0
如你所见,指针值传递成功。但是,打印出的值是错误的。
我在传递数组给C函数时是否做错了什么?
英文:
I was struggling with OpenGL ES. It didn't worked well.
And I got similar thing working in C.(I just copied Go code and modified(syntax) and removed(non-important function call) some things for C.)
I finally found that Go arrays were not passed to C function.(So, arrays as vertex array, indices couldn't be passed well and did something wrong when I render.)
I tested with this code:
C function part:
void passTest(void *Ptr){
int *test = (GLfloat *)Ptr;
printf("C: test=%p\n", test);
printf("C: test[0]=%d\ntest[1]=%d\ntest[2]=%d\ntest[3]=%d\n", test[0], test[1], test[2], test[3]);
}
And this is Go part:
test := []int{ 0, 3, 9, 81018 }
var ptr unsafe.Pointer = (unsafe.Pointer)(&test)
fmt.Printf("Go: test=%p\n", ptr)
fmt.Printf("Go: test[0]=%d\ntest[1]=%d\ntest[2]=%d\ntest[3]=%d\n", test[0], test[1], test[2], test[3])
C.passTest(ptr)
Result is:
Go: test=0x10300010
Go: test[0]=0
test[1]=3
test[2]=9
test[3]=81018
C: test=0x10300010
C: test[0]=271581216
test[1]=4
test[2]=4
test[3]=0
As you can see, pointer value passed well. But, printed value is wrong.
Am I doing something wrong with passing arrays to C?
答案1
得分: 0
这对于数组是正确的,但是这里你有一个切片。使用第一个元素的地址来获取底层数组的地址。
ptr := unsafe.Pointer(&test[0])
英文:
That's correct for an array, but here you have a go slice. Use the address of the first element to get the address of the underlying array
ptr := unsafe.Pointer(&test[0])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论