使用ctypes将列表传递给Go map?

时间:2017-07-28 21:44:04

标签: python c go shared-libraries ctypes

我有一个go库,如:

//try_async.go
package main

import (
    "C"
    "fmt"
    "math/rand"
    "sync"
    "time"
)

var mutex sync.Mutex
var wg sync.WaitGroup

func random_sleep() {
    r := rand.Intn(3000)
    time.Sleep(time.Duration(r) * time.Millisecond)
}


func add_to_map(m map[string] string, word string) {
    defer wg.Done()
    added_word := word + " plus more letters"
    fmt.Println("Before sleep")
    random_sleep()
    mutex.Lock()
    defer mutex.Unlock()
    m[word] = added_word
    fmt.Println("Added word %v", word)
}

//export add_all_items_to_map
func add_all_items_to_map(words []string) map[string]string {
    words_map := make(map[string]string)
    for _, this_word := range words {
        wg.Add(1)
        go add_to_map(words_map, this_word)
    }
    wg.Wait()
    return words_map
}


func main() {
    // result := add_all_items_to_map([]string{"cat", "dog", "fish"})
    // fmt.Println(result)
}

python脚本成功调用它:

from ctypes import cdll

"""
run

  go build -buildmode=c-shared -o try_async.so try_async.go

first
"""

lib = cdll.LoadLibrary('./try_async.so')

print("Loaded go lib")
result = lib.add_all_items_to_map(['cat', 'dog', 'fish'])
print(result)

但是,我不知道如何将一个python列表传递给Go slice(我认为最接近的东西)或python dict到Go map(几乎相同):

$ go build -buildmode=c-shared -o try_async.so try_async.go

$ python go-async-caller.py
Loaded go lib
Traceback (most recent call last):
  File "go-async-caller.py", line 14, in <module>
    result = lib.add_all_items_to_map(['cat', 'dog', 'fish'])
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1

我期待一个python列表直接转换为Go slice。中间人是C.我怎样才能让这些python数据类型正确使用这个Go lib?

0 个答案:

没有答案