在Golang访问C数组
问题说明
我有两个文件, module.go
和 test.py
。我的目标是加快一些在python中完成的计算,但是在访问go中的整数数组时遇到问题。
I have two files, module.go
and test.py
. My goal is to speed up some calculations that is done in python, but have an issue accessing array of integers in go.
module.go
package main
import "C"
//export Example
func Example(testArray []C.int) C.int {
return testArray[2]
}
func main() {}
和python中的简单测试文件:
and simple test file in python:
from ctypes import *
# Load compiled go module
lib = cdll.LoadLibrary("./gomodule.so")
# We are passing an array of 256 elements and recieving integer
lib.Example.argtypes = [c_int * 256]
lib.Example.restype = c_int
pyarr = [x for x in range(256)]
# Make C array from py array
arr = (c_int * len(pyarr))(*pyarr)
print lib.Example(arr)
使用编译go模块后,请执行build -buildmode = c-shared -o gomodule.so模块。走
并启动我得到的python文件:
After compiling go module with go build -buildmode=c-shared -o gomodule.so module.go
and fire up python file I got:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x12 pc=0x7fb18b6e688c]
goroutine 17 [running, locked to thread]:
main.Example(...)
/home/metro/go/src/github.com/golubaca/carinago/module.go:7
main._cgoexpwrap_53c1c00d0ad3_Example(0xa, 0x7fff33a2eac0, 0x7fff33a2ea70, 0x722a921de6cae100)
_cgo_gotypes.go:47 0x1c
Aborted (core dumped)
我知道C数组与Go有所不同,但是找不到任何教程如何在没有恐慌的情况下访问它的值。 / p>
I get that C array is different from Go, but can't find any tutorial how to access it's values without panic.
正确答案
这是惯用的,有效的Go解决方案(避免反射)。
This is the idiomatic, efficient Go solution (avoid reflection).
module.go
:
package main
import "C"
import "unsafe"
//export Example
func Example(cArray *C.int, cSize C.int, i C.int) C.int {
gSlice := (*[1 << 30]C.int)(unsafe.Pointer(cArray))[:cSize:cSize]
return gSlice[i]
}
func main() {}
test.py
:
from ctypes import *
# Load compiled go module
lib = cdll.LoadLibrary("./gomodule.so")
# We are passing an array of 256 elements and receiving an integer
lib.Example.argtypes = [c_int * 256]
lib.Example.restype = c_int
pyarr = [x for x in range(256)]
# Make C array from py array
arr = (c_int * len(pyarr))(*pyarr)
print lib.Example(arr, len(arr), 4)
输出:
$ go build -buildmode=c-shared -o gomodule.so module.go
$ python test.py
4
$
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfkbai
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20