sbinet / go-python

naive go bindings to the CPython2 C-API
Other
1.53k stars 138 forks source link

I don't known how to use cPickle, help me, #29

Closed tangleiao closed 8 years ago

tangleiao commented 8 years ago

I don't known how to use cPickle, help me; Can you give me a example? Thanks a lot

sbinet commented 8 years ago

hi,

could you give some more informations about you are trying to achieve?

the following might help, if you want to simply pickle a python object:

package main

import (
    "fmt"

    "github.com/sbinet/go-python"
)

func init() {
    err := python.Initialize()
    if err != nil {
        panic(err.Error())
    }
}

func main() {
    gostr := "foo"
    pystr := python.PyString_FromString(gostr)
    str := python.PyString_AsString(pystr)
    fmt.Println("hello [", str, "]")

    pickle := python.PyImport_ImportModule("cPickle")
    if pickle == nil {
        panic("could not import 'cPickle'")
    }
    dumps := pickle.GetAttrString("dumps")
    if dumps == nil {
        panic("could not retrieve 'cPickle.dumps'")
    }
    out := dumps.CallFunctionObjArgs("O", pystr)
    if out == nil {
        panic("could not dump pystr")
    }
    fmt.Printf("cPickle.dumps(%s) = %q\n", gostr,
        python.PyString_AsString(out),
    )
}

which gives:

$ go run ./main.go
hello [ foo ]
cPickle.dumps(foo) = "S'foo'\np1\n."
tangleiao commented 8 years ago

Thank you very much