1

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.

Reference

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)
JimB
  • 104,193
  • 13
  • 262
  • 255
D3XT3R
  • 181
  • 2
  • 15

0 Answers0