我已经解决了这个问题,请参阅问题下面的答案。
但我最终发现将GO函数嵌入到Python中是非常愚蠢的。这种嵌入失败主要是因为Go函数几乎不知道何时回收内存资源,从而导致内存泄漏。
目前,我意识到将它们组合在一起的最好方法可能是信息交流,就像袜子一样。
如果我的想法是错误的,请告诉我任何正确的事情。
原始问题:
在 C 端,函数返回一个字符串数组(例如 [“i 0”、“i 1”、“i 2”、“i 3”]),类型为 。**char
在 Python 端,该输出被读入一个变量(比如说),其类型为**charcArrayPOINTER(c_char_p)
我的问题:如何创建一个python列表?即获得cArraypylist == ["i 0","i 1","i 2","i 3"]
我还想知道在python中是否有一个值获取操作,就像C中的*操作一样。
下面是代码示例:
C面(实际去)
package main
//#include <stdlib.h>
import "C"
import (
"unsafe"
)
//export TestLoad
func TestLoad(cstr *C.char) **C.char {
gostr := C.GoString(cstr)
goslice := []string{gostr, "i 0", "i 1", "i 2", "i 3"}
cArray := C.malloc(C.size_t(len(goslice)) * C.size_t(unsafe.Sizeof(uintptr(0))))
defer C.free(unsafe.Pointer(cArray))
temp := (*[1<<30 - 1]*C.char)(cArray)
for k, v := range goslice {
temp[k] = C.CString(v)
}
return (**C.char)(cArray)
}
func main() {
}
蟒蛇侧
from ctypes import *
mylib = cdll.LoadLibrary("./mylib.so")
mylib.TestLoad.argtype = c_char_p
mylib.TestLoad.restype = POINTER(c_char_p) # ***Is it possible to have two or more restypes?***
pystr = "hello" # python str
b = pystr.encode("utf-8") # convert str to bytes
resp = mylib.TestLoad(b) # call CGo function, and get resp typed POINTER(c_char_p)
list_len = 5 # assume the length of list is known
'''
TODO
'''
顺便说一句,单个C或CGO函数是否有可能具有两个或多个返回?我尝试过,但未能成功。
感谢您的帮助。
缥缈止盈
相关分类