【发布时间】:2021-02-26 08:03:57
【问题描述】:
我有一个名为 test.go 的模块,其中包含两个接受字符串类型的简单 Go 函数:
package main
import (
"fmt"
"C"
)
//export TestConcat
func TestConcat(testArg string, testArg2 string) (string) {
retval := testArg + testArg2
return retval
}
//export TestHello
func TestHello(testArg string) {
fmt.Println("%v\n", testArg)
}
func main(){}
我将它编译为go build -o test.so -buildmode=c-shared test.go的共享库
然后我有一个名为test.py的Python模块
import ctypes
from ctypes import cdll
test_strings = [
"teststring1",
"teststring2"
]
if __name__ == '__main__':
lib = cdll.LoadLibrary("./test.so")
lib.TestConcat.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p]
lib.TestHello.argtypes = [ctypes.c_wchar_p]
for test_string in test_strings:
print(
lib.TestConcat("hello", test_string)
)
lib.TestHello(test_string)
然后我运行 test.py 并得到一个讨厌的段错误
runtime: out of memory: cannot allocate 279362762964992-byte block (66781184 in use)
fatal error: out of memory
我尝试将参数包装在 ctypes.c_wchar_p 中,但无济于事。
我在这里做错了什么?具体来说,如何与 Python 中接受字符串参数的 Go 函数进行交互?
【问题讨论】: