Reputation: 171
I am trying to return []string from golang to list in my python program. I am successfully able to convert go slice into c array from some of the references from stackoverflow.
But I am not sure on how to convert back into python list.
Any pointers would be appreciated.
Thanks.
Here are my code examples.
// example.go
package main
import "C"
import (
"unsafe"
)
//export Example
func Example() **C.char {
// len of slice may be dynamic
data := []string {
"A",
"B",
"C",
}
cArray := C.malloc(C.size_t(len(data)) * C.size_t(unsafe.Sizeof(uintptr(0))))
a := (*[1<<30 - 1]*C.char)(cArray)
for i, value := range data {
a[i] = C.CString(value)
}
return (**C.char)(cArray)
}
func main() {}
# example.py
from ctypes import *
lib = cdll.LoadLibrary('./example.so')
lib.Example.argtypes = None
lib.Example.restype = POINTER(c_char_p)
ret_value = lib.Example()
mylist = [value for value in ret_value.contents]
print(mylist)
Upvotes: 1
Views: 407
Reputation: 5910
You can do that with MetaFFI
Assume this SplitStrings.go
func SplitStringByComma(input string) []string {
return strings.Split(input, ",")
}
use MetaFFI compiler to compile to a shared object (.so or .dll):
metaffi -c --idl SplitStrings.go -g
This creates SplitStrings_MetaFFIGuest.[so/.dll]
Next, in Python, load the shared object and load the function:
import metaffi # get metaffi-api package from PIP
# load Go runtime plugin
runtime = metaffi.metaffi_runtime.MetaFFIRuntime('go')
runtime.load_runtime_plugin()
# load module
split_module = runtime.load_module('SplitStrings_MetaFFIGuest.so')
# load function
# define return type, you don't have to predefine the dimensions, but it can improve performance.
ret_type = [metaffi.metaffi_types.metaffi_type_info(metaffi.metaffi_types.MetaFFITypes.metaffi_string8_array_type, dims=1)]
# define parameters type
params_type = [metaffi.metaffi_types.metaffi_type_info(metaffi.metaffi_types.MetaFFITypes.metaffi_string8_type)]
# load the function
split_strings_by_comma = split_module.load_entity('callable=SplitStringByComma', params_type, ret_type)
# use it
res = split_strings_by_comma('one,two,three')
Disclaimer: I am the author of MetaFFI
Upvotes: 0