forked from sbinet/go-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.go
85 lines (68 loc) · 2.07 KB
/
heap.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package python
/*
#include <Python.h>
#include <stdlib.h>
static PyObject* _gopy_InitModule(const char* nm, PyMethodDef* methods) {
return Py_InitModule(nm, methods);
}
static PyObject* _gopy_InitModule3(const char* nm, PyMethodDef* methods, const char *doc) {
return Py_InitModule3(nm, methods, doc);
}
static PyMethodDef* _gopy_malloc_PyMethodDefArray(size_t n) {
return (PyMethodDef*)malloc(n * sizeof(PyMethodDef));
}
static void _gopy_set_PyMethodDef(PyMethodDef *array, int i, PyMethodDef *o) {
array[i] = *o;
}
*/
import "C"
import (
"errors"
"unsafe"
)
var (
gModules = make(map[string]unsafe.Pointer) // register of [modules - method-definitions]
)
// cpyMethodDefs creates a C-array of C.PyMethodDef, with a {0} sentinel
// FIXME(sbinet) convert 'methods' to a *C.PyMethodDef
func cpyMethodDefs(name string, methods []PyMethodDef) *C.PyMethodDef {
if len(methods) <= 0 {
return nil
}
n := C.size_t(len(methods) + 1)
cmeths := C._gopy_malloc_PyMethodDefArray(n)
for i, meth := range methods {
cmeth := C.PyMethodDef{
ml_name: C.CString(meth.Name),
ml_meth: (C.PyCFunction)(unsafe.Pointer(&meth.Meth)),
ml_flags: C.int(meth.Flags),
ml_doc: C.CString(meth.Doc),
}
C._gopy_set_PyMethodDef(cmeths, C.int(i), &cmeth)
}
gModules[name] = unsafe.Pointer(cmeths)
return cmeths
}
func Py_InitModule(name string, methods []PyMethodDef) (*PyObject, error) {
c_mname := C.CString(name)
defer C.free(unsafe.Pointer(c_mname))
cmeths := cpyMethodDefs(name, methods)
obj := togo(C._gopy_InitModule(c_mname, cmeths))
if obj == nil {
return nil, errors.New("python: internal error; module creation failed.")
}
return obj, nil
}
func Py_InitModule3(name string, methods []PyMethodDef, doc string) (*PyObject, error) {
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
cdoc := C.CString(doc)
defer C.free(unsafe.Pointer(cdoc))
cmeths := cpyMethodDefs(name, methods)
obj := togo(C._gopy_InitModule3(cname, cmeths, cdoc))
if obj == nil {
return nil, errors.New("python: internal error; module creation failed.")
}
return obj, nil
}
// EOF