如何将Go数组传递给C?

huangapple go评论70阅读模式
英文:

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])

huangapple
  • 本文由 发表于 2016年1月17日 21:53:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/34839113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定