如何解决从 **char 到 python 列表
我已经解决了问题,请在问题下方查看我的回答。
但我最终发现将 GO 函数嵌入到 Python 中非常愚蠢。这种嵌入失败主要是因为 Go 函数很难知道什么时候回收内存资源,从而导致内存泄漏。
目前,我意识到将它们组合在一起的最佳方式可能是消息通信,就像袜子一样。
如果我的想法有误,请告诉我正确的地方。
原始问题:
在 C 端,函数返回一个字符串数组(比如 ["i 0","i 1","i 2","i 3"]),类型为 **char
。
在 Python 端,**char
输出被读入一个变量(比如 cArray
),类型为 POINTER(c_char_p)
我的问题:如何从 cArray
创建一个 python 列表?即获得 pylist == ["i 0","i 3"]
我也想知道python中有没有取值操作,比如C中的*操作。
以下是代码示例:
C 端(实际上是 Go)
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 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() {
}
Python 端
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 函数是否可能有两个或多个回报?我试过了,但编译失败。
感谢您的帮助。
解决方法
解决方案:
C侧(GO) -- defer C.free...
所在的那一行应该是评论
package main
//#include <stdlib.h>
import "C"
import (
"fmt"
"unsafe"
)
//export TestLoad
func TestLoad(cstr *C.char) **C.char {
gostr := C.GoString(cstr)
fmt.Println("In Go: ",gostr)
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() {
}
Python 端 --修改:POINTER(c_char_p * 5),然后调用 resp.contents 访问每个 python 字节。有关来源,请参阅 Example #17。
from ctypes import *
mylib = cdll.LoadLibrary("./_mylib.so")
mylib.TestLoad.argtype = c_char_p
mylib.TestLoad.restype = POINTER(c_char_p*5)
pystr = "Hello,world!"
b = pystr.encode("utf-8")
resp = mylib.TestLoad(b)
'''**********************************'''
output = []
for seq in resp.contents:
s = seq.decode("utf-8")
output.append(s)
print(s,type(s))
print(output)
'''**********************************'''
出现了一个新问题:
在此示例中,注释 // defer C.free(unsafe.Pointer(cArray))
会导致 C 端内存泄漏吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。