Exemplo n.º 1
0
func NewGoModule(name string, doc string, self interface{}) (mod GoModule, err error) {

	cName := C.CString(name)
	defer C.free(unsafe.Pointer(cName))

	var mdoc *C.char
	if doc != "" {
		mdoc = C.CString(doc)
		defer C.free(unsafe.Pointer(mdoc))
	}

	m := C.Py_InitModule4(cName, nil, mdoc, nil, C.PYTHON_API_VERSION)
	if m == nil {
		err = exception()
		return
	}

	mod.Module = (*Module)(unsafe.Pointer(m))
	mod.Ctx = Register(mod.Module.Dict(), name+".", self)
	return
}
Exemplo n.º 2
0
func InitModule(name string, methods []Method) (*Module, error) {
	cName := C.CString(name)
	defer C.free(unsafe.Pointer(cName))

	m := C.Py_InitModule4(cName, nil, nil, nil, C.PYTHON_API_VERSION)
	if m == nil {
		return nil, exception()
	}

	if len(methods) == 0 {
		return newModule(m), nil
	}

	n := C.PyString_FromString(cName)
	if n == nil {
		return nil, exception()
	}

	d := C.PyModule_GetDict(m)
	if d == nil {
		return nil, exception()
	}

	for _, method := range methods {
		pyF, err := makeCFunction(method.Name, method.Func, method.Doc, n)
		if err != nil {
			return nil, err
		}

		if C.PyDict_SetItemString(d, C.CString(method.Name), c(pyF)) != 0 {
			return nil, exception()
		}
	}

	return newModule(m), nil
}