Ejemplo n.º 1
0
Archivo: err.go Proyecto: runcom/gossl
func getErrorString(code C.ulong) string {
	if code == 0 {
		return ""
	}
	msg := fmt.Sprintf("%s:%s:%s\n",
		C.GoString(C.ERR_lib_error_string(code)),
		C.GoString(C.ERR_func_error_string(code)),
		C.GoString(C.ERR_reason_error_string(code)))
	if len(msg) == 4 { //being lazy here, all the strings were empty
		return ""
	}
	//Check for extra line data
	var file *C.char
	var line C.int
	var data *C.char
	var flags C.int
	if int(C.ERR_get_error_line_data(&file, &line, &data, &flags)) != 0 {
		msg += fmt.Sprintf("%s:%s", C.GoString(file), int(line))
		if flags&C.ERR_TXT_STRING != 0 {
			msg += ":" + C.GoString(data)
		}
		if flags&C.ERR_TXT_MALLOCED != 0 {
			C.CRYPTO_free(unsafe.Pointer(data))
		}
	}
	return msg
}
Ejemplo n.º 2
0
func mruby2go(mrb *C.mrb_state, o C.mrb_value) interface{} {
	switch o.tt {
	case C.MRB_TT_TRUE:
		return true
	case C.MRB_TT_FALSE:
		return false
	case C.MRB_TT_FLOAT:
		return float32(C._mrb_float(o))
	case C.MRB_TT_FIXNUM:
		return int32(C._mrb_fixnum(o))
	case C.MRB_TT_ARRAY:
		{
			var list []interface{}
			for i := 0; i < int(C._RARRAY_LEN(o)); i++ {
				list = append(list, mruby2go(mrb, C.mrb_ary_ref(mrb, o, C.mrb_int(i))))
			}
			return list
		}
	case C.MRB_TT_HASH:
		{
			hash := make(map[string]interface{})
			keys := C.mrb_hash_keys(mrb, o)
			for i := 0; i < int(C._RARRAY_LEN(keys)); i++ {
				key := C.mrb_ary_ref(mrb, keys, C.mrb_int(i))
				val := C.mrb_hash_get(mrb, o, key)
				hash[C.GoString(C.mrb_string_value_ptr(mrb, key))] = mruby2go(mrb, val)
			}
			return hash
		}
	case C.MRB_TT_STRING:
		return C.GoString(C.mrb_string_value_ptr(mrb, o))
	}
	return nil
}
Ejemplo n.º 3
0
Archivo: pq.go Proyecto: dvarrazzo/pger
func connect(conninfo string) (*PgConn, error) {
	cs := C.CString(conninfo)
	defer C.free(unsafe.Pointer(cs))
	conn := C.PQconnectdb(cs)
	if C.PQstatus(conn) != C.CONNECTION_OK {
		cerr := C.PQerrorMessage(conn)
		err := fmt.Errorf("connection failed: %s", C.GoString(cerr))
		C.PQfinish(conn)
		return nil, err
	}

	// TODO: support other encodings?
	pname := C.CString("client_encoding")
	defer C.free(unsafe.Pointer(pname))
	cenc := C.PQparameterStatus(conn, pname)
	if cenc == nil {
		err := errors.New("connection failed: no client encoding")
		C.PQfinish(conn)
		return nil, err
	}
	if enc := C.GoString(cenc); enc != "UTF8" {
		err := fmt.Errorf(
			"connection failed: client encoding not supported: %s", enc)
		C.PQfinish(conn)
		return nil, err
	}

	// one-line error message
	C.PQsetErrorVerbosity(conn, C.PQERRORS_TERSE)

	return &PgConn{conn: conn, conninfo: conninfo}, nil
}
Ejemplo n.º 4
0
func Enum() []Info {
	fmt.Printf("")

	bus := C.usb_get_busses()
	n := 0
	for ; bus != nil; bus = bus.next {
		for dev := bus.devices; dev != nil; dev = dev.next {
			n += 1
		}
	}
	infos := make([]Info, n)

	bus = C.usb_get_busses()
	n = 0

	for ; bus != nil; bus = bus.next {
		busname := C.GoString(&bus.dirname[0])

		for dev := bus.devices; dev != nil; dev = dev.next {
			devname := C.GoString(&dev.filename[0])

			var info Info
			info.Bus = busname
			info.Device = devname
			info.Vid = int(dev.descriptor.idVendor)
			info.Pid = int(dev.descriptor.idProduct)

			infos[n] = info
			n += 1
		}
	}
	return infos
}
Ejemplo n.º 5
0
// LocalZone returns the *Zone. First it checks the ConnectionOptions.Zone and uses that, otherwise it pulls it fresh from the iCAT server.
func (con *Connection) LocalZone() (*Zone, error) {

	var (
		cZoneName *C.char
		err       *C.char
	)

	if con.Options.Zone == "" {
		ccon := con.GetCcon()
		if status := C.gorods_get_local_zone(ccon, &cZoneName, &err); status != 0 {
			con.ReturnCcon(ccon)
			return nil, newError(Fatal, fmt.Sprintf("iRODS Get Local Zone Failed: %v", C.GoString(err)))
		}
		con.ReturnCcon(ccon)
	} else {
		cZoneName = C.CString(con.Options.Zone)
	}

	defer C.free(unsafe.Pointer(cZoneName))

	zoneName := strings.Trim(C.GoString(cZoneName), " \n")

	if znes, err := con.Zones(); err != nil {
		return nil, err
	} else {
		if zne := znes.FindByName(zoneName, con); zne == nil {
			return nil, newError(Fatal, fmt.Sprintf("iRODS Get Local Zone Failed: Local zone not found in cache"))
		} else {
			return zne, nil
		}
	}

}
Ejemplo n.º 6
0
func lolwut() {
	runtime.LockOSThread()
	var stream unsafe.Pointer
	err := C.Pa_OpenDefaultStream(&stream,
		0,           // no input
		1,           // mono
		C.paFloat32, // 32-bit floating point
		48000,
		C.paFramesPerBufferUnspecified,
		nil,
		nil)
	if err != C.paNoError {
		panic(C.GoString(C.Pa_GetErrorText(err)))
	}
	err = C.Pa_StartStream(stream)
	if err != C.paNoError {
		panic(C.GoString(C.Pa_GetErrorText(err)))
	}
	for {
		err := C.Pa_WriteStream(stream, unsafe.Pointer(&genSine(440)[0]), 48000)
		if err != C.paNoError {
			panic(C.GoString(C.Pa_GetErrorText(err)))
		}
	}
}
Ejemplo n.º 7
0
// Open database and return a new connection.
// You can specify DSN string with URI filename.
//   test.db
//   file:test.db?cache=shared&mode=memory
//   :memory:
//   file::memory:
func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
	if C.sqlite3_threadsafe() == 0 {
		return nil, errors.New("sqlite library was not compiled for thread-safe operation")
	}

	var db *C.sqlite3
	name := C.CString(dsn)
	defer C.free(unsafe.Pointer(name))
	rv := C._sqlite3_open_v2(name, &db,
		C.SQLITE_OPEN_FULLMUTEX|
			C.SQLITE_OPEN_READWRITE|
			C.SQLITE_OPEN_CREATE,
		nil)
	if rv != 0 {
		return nil, errors.New(C.GoString(C.sqlite3_errmsg(db)))
	}
	if db == nil {
		return nil, errors.New("sqlite succeeded without returning a database")
	}

	rv = C.sqlite3_busy_timeout(db, 5000)
	if rv != C.SQLITE_OK {
		return nil, errors.New(C.GoString(C.sqlite3_errmsg(db)))
	}

	return &SQLiteConn{db}, nil
}
Ejemplo n.º 8
0
//export AddRequire
func AddRequire(cTarget uintptr, cRequire *C.char) *C.char {
	target := unsizet(cTarget)
	target.Requires = append(target.Requires, C.GoString(cRequire))
	// Requirements are also implicit labels
	target.AddLabel(C.GoString(cRequire))
	return nil
}
Ejemplo n.º 9
0
// Returns all metadata keys from the currently loaded image.
func (self *Canvas) Metadata() map[string]string {
	var n C.size_t
	var i C.size_t

	var value *C.char
	var key *C.char

	data := make(map[string]string)

	cplist := C.CString("*")

	properties := C.MagickGetImageProperties(self.wand, cplist, &n)

	C.free(unsafe.Pointer(cplist))

	for i = 0; i < n; i++ {
		key = C.MagickGetPropertyName(properties, C.size_t(i))
		value = C.MagickGetImageProperty(self.wand, key)

		data[strings.Trim(C.GoString(key), " ")] = strings.Trim(C.GoString(value), " ")

		C.MagickRelinquishMemory(unsafe.Pointer(value))
		C.MagickRelinquishMemory(unsafe.Pointer(key))
	}

	return data
}
Ejemplo n.º 10
0
func GetAllSchemeDetails() []*SchemeDetails {
	allHandles := C.varnam_get_all_handles()
	if allHandles == nil {
		return []*SchemeDetails{}
	}

	var schemeDetails []*SchemeDetails
	length := int(C.varray_length(allHandles))
	for i := 0; i < length; i++ {
		handle := (*C.varnam)(C.varray_get(allHandles, C.int(i)))
		var detail *C.vscheme_details
		rc := C.varnam_get_scheme_details(handle, &detail)
		if rc != C.VARNAM_SUCCESS {
			return []*SchemeDetails{}
		}

		schemeDetails = append(schemeDetails, &SchemeDetails{
			LangCode: C.GoString(detail.langCode), Identifier: C.GoString(detail.identifier),
			DisplayName: C.GoString(detail.displayName), Author: C.GoString(detail.author),
			CompiledDate: C.GoString(detail.compiledDate), IsStable: detail.isStable > 0})

		C.varnam_destroy(handle)
	}

	return schemeDetails
}
Ejemplo n.º 11
0
//export go_make_message
func go_make_message(
	message, source_line, script_resource_name *C.char,
	stack_trace unsafe.Pointer,
	line, start_pos, end_pos, start_col, end_col int,
) unsafe.Pointer {

	go_message := &Message{
		C.GoString(message),
		C.GoString(source_line),
		C.GoString(script_resource_name),
		nil,
		line,
		start_pos,
		end_pos,
		start_col,
		end_col,
	}

	if stack_trace != nil {
		go_message.StackTrace = *(*StackTrace)(stack_trace)
	}

	if go_message.ScriptResourceName == "undefined" {
		go_message.ScriptResourceName = ""
	}

	maybe_free(unsafe.Pointer(message))
	maybe_free(unsafe.Pointer(source_line))
	maybe_free(unsafe.Pointer(script_resource_name))

	return unsafe.Pointer(go_message)
}
Ejemplo n.º 12
0
//export Zip
func Zip(zipname *C.char, filenames []*C.char) int32 {
	f, err := os.Create(C.GoString(zipname))
	if err != nil {
		log.Println(err)
		return -1
	}
	defer f.Close()

	w := zip.NewWriter(f)
	defer w.Close()

	for _, name := range filenames {
		ww, err := w.Create(C.GoString(name))
		if err != nil {
			log.Println(err)
			return -1
		}

		fi, err := os.Open(C.GoString(name))
		if err != nil {
			log.Println(err)
			return -1
		}
		defer fi.Close()

		if _, err := io.Copy(ww, fi); err != nil {
			log.Println(err)
			return -1
		}
	}

	return 0
}
Ejemplo n.º 13
0
Archivo: index.go Proyecto: wid/git2go
//export indexMatchedPathCallback
func indexMatchedPathCallback(cPath, cMatchedPathspec *C.char, payload unsafe.Pointer) int {
	if callback, ok := pointerHandles.Get(payload).(IndexMatchedPathCallback); ok {
		return callback(C.GoString(cPath), C.GoString(cMatchedPathspec))
	} else {
		panic("invalid matched path callback")
	}
}
Ejemplo n.º 14
0
//export exec_xpath_function
func exec_xpath_function(ctxt C.xmlXPathParserContextPtr, nargs C.int) {
	function := C.GoString((*C.char)(unsafe.Pointer(ctxt.context.function)))
	namespace := C.GoString((*C.char)(unsafe.Pointer(ctxt.context.functionURI)))
	context := (*VariableScope)(ctxt.context.funcLookupData)

	argcount := int(nargs)
	var args []interface{}

	for i := 0; i < argcount; i = i + 1 {
		args = append(args, XPathObjectToValue(C.valuePop(ctxt)))
	}

	// arguments are popped off the stack in reverse order, so
	// we reverse the slice before invoking our callback
	if argcount > 1 {
		for i, j := 0, len(args)-1; i < j; i, j = i+1, j-1 {
			args[i], args[j] = args[j], args[i]
		}
	}

	// push the result onto the stack
	// if for some reason we are unable to resolve the
	// function we push an empty nodeset
	f := (*context).ResolveFunction(function, namespace)
	if f != nil {
		retval := f(*context, args)
		C.valuePush(ctxt, ValueToXPathObject(retval))
	} else {
		ret := C.xmlXPathNewNodeSet(nil)
		C.valuePush(ctxt, ret)
	}

}
Ejemplo n.º 15
0
//GetUnitDefinition Get the nth GetUnitDefinition object in this Model.
func (m *Model) GetUnitDefinition(n int) (ud *UnitDefinition) {
	ud = new(UnitDefinition)
	ud.ud = C.Model_getUnitDefinition(m.m, C.uint(n))
	ud.ID = C.GoString(C.UnitDefinition_getId(ud.ud))
	ud.Name = C.GoString(C.UnitDefinition_getName(ud.ud))
	return ud
}
Ejemplo n.º 16
0
Archivo: core.go Proyecto: Gwill/go-R
func Eval(expression string) (*Result, error) {

	var status C.ParseStatus

	cmd := C.CString(expression)
	defer C.free(unsafe.Pointer(cmd))

	cmdRChar := C.mkChar(cmd)
	protector := Protect(cmdRChar)
	defer protector.Unprotect()

	cmdSexp := C.allocVector(C.STRSXP, 1)
	protector.Protect(cmdSexp)

	C.SET_STRING_ELT(cmdSexp, 0, cmdRChar)

	parsedCmd := C.R_ParseVector(cmdSexp, -1, (*C.ParseStatus)(unsafe.Pointer(&status)), C.R_NilValue)
	if status != C.PARSE_OK {
		return nil, fmt.Errorf("Invalid command: %s", C.GoString(cmd))
	}

	protector.Protect(parsedCmd)

	var result C.SEXP
	errorOccured := 0
	/* Loop is needed here as EXPSEXP will be of length > 1 */
	for i := 0; i < int(C.Rf_length(parsedCmd)); i++ {
		result = C.R_tryEval(C.VECTOR_ELT(parsedCmd, C.R_xlen_t(i)), C.R_GlobalEnv, (*C.int)(unsafe.Pointer(&errorOccured))) //R 3.0
		if errorOccured != 0 {
			return nil, fmt.Errorf("R error occured executing: %s", C.GoString(cmd))
		}
	}
	return NewResult(result), nil
}
Ejemplo n.º 17
0
Archivo: osr.go Proyecto: sn-amber/gdal
// Fetch information about a single parameter of a projection method
func ParameterInfo(
	projectionMethod, parameterName string,
) (
	username, paramType string,
	defaultValue float64,
	ok bool,
) {
	cMethod := C.CString(projectionMethod)
	defer C.free(unsafe.Pointer(cMethod))

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

	var cUserName *C.char
	var cParamType *C.char
	var cDefaultValue C.double

	success := C.OPTGetParameterInfo(
		cMethod,
		cName,
		&cUserName,
		&cParamType,
		&cDefaultValue)
	return C.GoString(cUserName), C.GoString(cParamType), float64(cDefaultValue), success != 0
}
Ejemplo n.º 18
0
//export swift_io_v_impl_google_rpc_ClientImpl_nativeStartCallAsync
func swift_io_v_impl_google_rpc_ClientImpl_nativeStartCallAsync(ctxHandle C.GoContextHandle, cName *C.char, cMethod *C.char, cVomArgs C.SwiftByteArrayArray, skipServerAuth bool, asyncId C.AsyncCallbackIdentifier, successCallback C.SwiftAsyncSuccessHandleCallback, failureCallback C.SwiftAsyncFailureCallback) {
	name := C.GoString(cName)
	method := C.GoString(cMethod)
	ctx := scontext.GoContext(uint64(ctxHandle))
	client := v23.GetClient(ctx)

	// TODO Get args (we don't have VOM yet in Swift so nothing to get until then)
	//	args, err := decodeArgs(env, jVomArgs)
	//	if err != nil {
	//		sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(errOut))
	//		return C.GoClientCallHandle(0)
	//	}
	args := make([]interface{}, 0)

	go func() {
		result, err := doStartCall(ctx, name, method, skipServerAuth == true, client, args)
		if err != nil {
			var swiftVError C.SwiftVError
			sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(&swiftVError))
			sutil.DoFailureCallback(unsafe.Pointer(failureCallback), int32(asyncId), unsafe.Pointer(&swiftVError))
		} else {
			handle := C.GoClientCallHandle(SwiftClientCall(result))
			sutil.DoSuccessHandlerCallback(unsafe.Pointer(successCallback), int32(asyncId), uint64(handle))
		}
	}()
}
Ejemplo n.º 19
0
Archivo: gl.go Proyecto: extrame/gl
// Link links the attached shader objects
func (p *Program) Link() error {
	var val, val2 C.GLint
	C.glLinkProgram(p.i)
	C.glGetProgramiv(p.i, LINK_STATUS, &val)
	if val != TRUE {
		C.glGetProgramiv(p.i, INFO_LOG_LENGTH, &val)
		buf := make([]C.GLchar, val+1)
		C.glGetProgramInfoLog(p.i, C.GLsizei(val), nil, &buf[0])
		return errors.New(C.GoString((*C.char)(&buf[0])))
	}
	p.attr = make(map[string]C.GLuint)
	C.glGetProgramiv(p.i, ACTIVE_ATTRIBUTES, &val)
	C.glGetProgramiv(p.i, ACTIVE_ATTRIBUTE_MAX_LENGTH, &val2)
	buf := make([]C.char, val2)
	for i := C.GLuint(0); i < C.GLuint(val); i++ {
		C.glGetActiveAttrib(p.i, i, C.GLsizei(val2), nil, nil, nil, (*C.GLchar)(&buf[0]))
		p.attr[C.GoString(&buf[0])] = C.GLuint(C.glGetAttribLocation(p.i, (*C.GLchar)(&buf[0])))
	}
	p.uni = make(map[string]C.GLint)
	C.glGetProgramiv(p.i, ACTIVE_UNIFORMS, &val)
	C.glGetProgramiv(p.i, ACTIVE_UNIFORM_MAX_LENGTH, &val2)
	buf = make([]C.char, val2)
	for i := C.GLuint(0); i < C.GLuint(val); i++ {
		C.glGetActiveUniform(p.i, i, C.GLsizei(val2), nil, nil, nil, (*C.GLchar)(&buf[0]))
		p.uni[C.GoString(&buf[0])] = C.glGetUniformLocation(p.i, (*C.GLchar)(&buf[0]))
	}
	return nil
}
Ejemplo n.º 20
0
// MkTemp creates a temporary file in the guest operating system.
// The user is responsible for removing the file when it is no longer needed.
//
// Since VMware Workstation 6.0
// Minimum Supported Guest OS: Microsoft Windows NT Series, Linux
func (g *Guest) MkTemp() (string, error) {
	var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
	var err C.VixError = C.VIX_OK
	var tempFilePath *C.char

	jobHandle = C.VixVM_CreateTempFileInGuest(g.handle,
		0,                    // options
		C.VIX_INVALID_HANDLE, // propertyListHandle
		nil,                  // callbackProc
		nil)                  // clientData

	defer C.Vix_ReleaseHandle(jobHandle)

	err = C.get_temp_filepath(jobHandle, tempFilePath)
	defer C.Vix_FreeBuffer(unsafe.Pointer(tempFilePath))

	if C.VIX_OK != err {
		return "", &Error{
			Operation: "guest.MkTemp",
			Code:      int(err & 0xFFFF),
			Text:      C.GoString(C.Vix_GetErrorText(err, nil)),
		}
	}

	return C.GoString(tempFilePath), nil
}
Ejemplo n.º 21
0
func DecodePDUBody2(buffer *C.asn_buf_t, pdu *C.snmp_pdu_t) (SnmpError, bool) {
	var recv_len C.int32_t
	var ignored C.int32_t = 0
	var ret_code uint32

	if C.SNMP_V3 == pdu.version {
		if C.SNMP_SECMODEL_USM != pdu.security_model {
			return Errorf(SNMP_CODE_FAILED, "unsupport security model - %d", int(pdu.security_model)), false
		}

		if ret_code = C.snmp_pdu_decode_secmode(buffer, pdu); C.SNMP_CODE_OK != ret_code {
			return Error(SnmpResult(ret_code), C.GoString(C.snmp_pdu_get_error(pdu, ret_code))), false
		}
	}

	if ret_code = C.snmp_pdu_decode_scoped2(buffer, pdu, &recv_len, &ignored); C.SNMP_CODE_OK != ret_code {
		switch ret_code {
		case C.SNMP_CODE_BADENC:
			if C.SNMP_Verr == pdu.version {
				return Errorf(SNMP_CODE_FAILED, "unsupport security model - %d", int(pdu.security_model)), false
			}
		}

		return Error(SnmpResult(ret_code), C.GoString(C.snmp_pdu_get_error(pdu, ret_code))), false
	}
	if 1 == ignored {
		return nil, true
	}
	return nil, false
}
Ejemplo n.º 22
0
Archivo: vox.go Proyecto: ajhager/vox
// Open creates a new slot and laods a sunvox song into it.
func Open(path string) (*Song, error) {
	slot := C.int(slots)
	if C.vox_open_slot(slot) != C.int(0) {
		return nil, errors.New("Could not open new slot")
	}

	name := C.CString(path)
	defer C.free(unsafe.Pointer(name))
	if C.vox_load(slot, name) != C.int(0) {
		return nil, errors.New(fmt.Sprintf("Could not open song %s", path))
	}

	slots++
	num_mods := int(C.vox_get_number_of_modules(slot))
	modules := make([]*Module, num_mods)
	for i := 0; i < num_mods; i++ {
		mod := new(Module)
		mod.num = C.int(i)
		mod.song = slot
		mod.name = C.GoString(C.vox_get_module_name(slot, C.int(i)))
		color := C.vox_get_module_color(slot, C.int(i))
		mod.red = byte(color & 255)
		mod.blue = byte((color >> 8) & 255)
		mod.green = byte((color >> 16) & 255)
		xy := C.vox_get_module_xy(slot, C.int(i))
		mod.x = int(xy >> 16)
		mod.y = int(xy & 0xffff)
		modules[i] = mod
	}
	song := &Song{slot, C.GoString(C.vox_get_song_name(slot)), 100, int(C.vox_get_song_bpm(slot)), int(C.vox_get_song_tpl(slot)), int(C.vox_get_song_length_frames(slot)), int(C.vox_get_song_length_lines(slot)), modules}
	song.SetVolume(song.volume)
	return song, nil
}
Ejemplo n.º 23
0
// Close closes a database connection and any dangling statements.
// (See http://sqlite.org/c3ref/close.html)
func (c *Conn) Close() error {
	if c == nil {
		return errors.New("nil sqlite database")
	}
	if c.db == nil {
		return nil
	}

	c.stmtCache.flush()

	// Dangling statements
	stmt := C.sqlite3_next_stmt(c.db, nil)
	for stmt != nil {
		if C.sqlite3_stmt_busy(stmt) != 0 {
			Log(C.SQLITE_MISUSE, "Dangling statement (not reset): \""+C.GoString(C.sqlite3_sql(stmt))+"\"")
		} else {
			Log(C.SQLITE_MISUSE, "Dangling statement (not finalize): \""+C.GoString(C.sqlite3_sql(stmt))+"\"")
		}
		C.sqlite3_finalize(stmt)
		stmt = C.sqlite3_next_stmt(c.db, nil)
	}

	rv := C.sqlite3_close(c.db)
	if rv != C.SQLITE_OK {
		Log(int(rv), "error while closing Conn")
		return c.error(rv, "Conn.Close")
	}
	c.db = nil
	return nil
}
Ejemplo n.º 24
0
Archivo: config.go Proyecto: wid/git2go
func newConfigEntryFromC(centry *C.git_config_entry) *ConfigEntry {
	return &ConfigEntry{
		Name:  C.GoString(centry.name),
		Value: C.GoString(centry.value),
		Level: ConfigLevel(centry.level),
	}
}
Ejemplo n.º 25
0
// Watcher callback
//export watcherCallback
func watcherCallback(
	watchId C.efsw_watchid,
	directory,
	filename *C.char,
	action C.int,
	oldFilename *C.char,
) {
	// Lock the watch-to-channel map for reading
	lock.Lock()
	defer lock.Unlock()

	// Get the event channel, ignoring the callback if we can't find it, because
	// the channel may have been removed from the dispatch map by DeleteWatch
	// before the watcher thread managed to post the event
	channel := dispatchMap[watchId]
	if channel == nil {
		return
	}

	// Create the event
	event := Event{
		C.GoString(directory),
		C.GoString(filename),
		int(action),
		C.GoString(oldFilename),
	}

	// Dispatch the event if immediately possible, otherwise discard it
	select {
	case channel <- event:
	default:
	}
}
Ejemplo n.º 26
0
Archivo: driver.go Proyecto: rsc/sqlite
func (s *stmt) Query(args []driver.Value) (driver.Rows, error) {
	if s.closed {
		panic("database/sql/driver: misuse of sqlite driver: Query after Close")
	}
	if s.rows {
		panic("database/sql/driver: misuse of sqlite driver: Query with active Rows")
	}

	err := s.start(args)
	if err != nil {
		return nil, err
	}

	s.rows = true
	if s.colnames == nil {
		n := int64(C.sqlite3_column_count(s.stmt))
		s.colnames = make([]string, n)
		s.coltypes = make([]string, n)
		for i := range s.colnames {
			s.colnames[i] = C.GoString(C.sqlite3_column_name(s.stmt, C.int(i)))
			s.coltypes[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(s.stmt, C.int(i))))
		}
	}
	return &rows{s}, nil
}
Ejemplo n.º 27
0
func Findalldevs() (ifs []Interface, err error) {
	var buf *C.char
	buf = (*C.char)(C.calloc(ERRBUF_SIZE, 1))
	defer C.free(unsafe.Pointer(buf))
	var alldevsp *C.pcap_if_t

	if -1 == C.pcap_findalldevs((**C.pcap_if_t)(&alldevsp), buf) {
		return nil, errors.New(C.GoString(buf))
	}
	defer C.pcap_freealldevs((*C.pcap_if_t)(alldevsp))
	dev := alldevsp
	var i uint32
	for i = 0; dev != nil; dev = (*C.pcap_if_t)(dev.next) {
		i++
	}
	ifs = make([]Interface, i)
	dev = alldevsp
	for j := uint32(0); dev != nil; dev = (*C.pcap_if_t)(dev.next) {
		var iface Interface
		iface.Name = C.GoString(dev.name)
		iface.Description = C.GoString(dev.description)
		iface.Addresses = findalladdresses(dev.addresses)
		// TODO: add more elements
		ifs[j] = iface
		j++
	}
	return
}
Ejemplo n.º 28
0
//GetFunctionDefinition Get the nth FunctionDefinitions object in this Model.
func (m *Model) GetFunctionDefinition(n int) (fd *FunctionDefinition) {
	fd = new(FunctionDefinition)
	fd.f = C.Model_getFunctionDefinition(m.m, C.uint(n))
	fd.Name = C.GoString(C.FunctionDefinition_getName(fd.f))
	fd.ID = C.GoString(C.FunctionDefinition_getId(fd.f))
	return fd
}
Ejemplo n.º 29
0
// Prepare query string. Return a new statement.
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
	pquery := C.CString(query)
	defer C.free(unsafe.Pointer(pquery))
	var s *C.sqlite3_stmt
	var tail *C.char
	rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &tail)
	if rv != C.SQLITE_OK {
		return nil, c.lastError()
	}
	var t string
	if tail != nil && *tail != '\000' {
		t = strings.TrimSpace(C.GoString(tail))
	}
	nv := int(C.sqlite3_bind_parameter_count(s))
	var nn []string
	for i := 0; i < nv; i++ {
		pn := C.GoString(C.sqlite3_bind_parameter_name(s, C.int(i+1)))
		if len(pn) > 1 && pn[0] == '$' && 48 <= pn[1] && pn[1] <= 57 {
			nn = append(nn, C.GoString(C.sqlite3_bind_parameter_name(s, C.int(i+1))))
		}
	}
	ss := &SQLiteStmt{c: c, s: s, nv: nv, nn: nn, t: t}
	runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
	return ss, nil
}
Ejemplo n.º 30
0
func (client *Client) runForever() {
	for {
		select {
		case <-client.closeChan:
			return
		default:
			C.replicant_client_block(client.ptr, 250)
			var loop_status C.enum_replicant_returncode
			client.mutex.Lock()
			reqid := int64(C.replicant_client_loop(client.ptr, 0, &loop_status))
			if reqid < 0 && loop_status == TIMEOUT {
				// pass
			} else if reqid < 0 && loop_status == NONE_PENDING {
				// pass
			} else if reqid < 0 && loop_status == INTERRUPTED {
				// pass
			} else if reqid < 0 {
				e := Error{Status(loop_status),
					C.GoString(C.replicant_client_error_message(client.ptr)),
					C.GoString(C.replicant_client_error_location(client.ptr))}
				client.errChan <- e
			} else if c, ok := (client.ops)[reqid]; ok {
				e := Error{Status(loop_status),
					C.GoString(C.replicant_client_error_message(client.ptr)),
					C.GoString(C.replicant_client_error_location(client.ptr))}
				c <- e
				delete(client.ops, reqid)
			}
			client.mutex.Unlock()
		}
	}
}