forked from goplus/py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.go
48 lines (40 loc) · 979 Bytes
/
string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package py
// #include <Python.h>
// static inline int stringCheck(PyObject *o) { return PyString_Check(o); }
import "C"
import "unsafe"
type String struct {
Base
o C.PyStringObject
}
// StringType is the Type object that represents the String type.
var StringType = (*Type)(unsafe.Pointer(&C.PyString_Type))
func newString(obj *C.PyObject) *String {
return (*String)(unsafe.Pointer(obj))
}
func NewString(s string) *String {
cs := C.CString(s)
defer C.free(unsafe.Pointer(cs))
ret := C.PyString_FromString(cs)
return newString(ret)
}
func AsString(o *Base) (v *String, ok bool) {
if ok = C.stringCheck(o.c()) != 0; ok {
v = newString(o.c())
}
return
}
func (s *String) String() string {
if s == nil {
return "<nil>"
}
ret := C.PyString_AsString(s.c())
return C.GoString(ret)
}
func (s *String) Format(args *Tuple) (*String, error) {
ret := C.PyString_Format(s.c(), args.c())
if ret == nil {
return nil, exception()
}
return newString(ret), nil
}