func toConfig(config C.struct_wireless_config) Config { c := Config{ Name: C.GoStringN(&config.name[0], C.IFNAMSIZ), HasNwid: int(config.has_nwid) == 1, HasFreq: int(config.has_freq) == 1, Freq: float64(config.freq), HasKey: int(config.has_key) == 1, Key: C.GoStringN((*C.char)(unsafe.Pointer(&config.key[0])), C.IW_ENCODING_TOKEN_MAX), KeySize: int(config.key_size), KeyFlags: int(config.key_flags), HasEssid: int(config.has_essid) == 1, EssidOn: int(config.essid_on) == 1, Essid: C.GoStringN(&config.essid[0], C.IW_ESSID_MAX_SIZE), HasMode: int(config.has_mode) == 1, Mode: int(config.mode), } if c.HasNwid { c.Nwid = IwParam{ Value: int(config.nwid.value), Fixed: int(config.nwid.fixed) == 1, Disabled: int(config.nwid.disabled) == 1, Flags: uint16(config.nwid.flags), } } return c }
// Get returns the username and secret to use for a given registry server URL. func (h Osxkeychain) Get(serverURL string) (string, string, error) { s, err := splitServer(serverURL) if err != nil { return "", "", err } defer freeServer(s) var usernameLen C.uint var username *C.char var secretLen C.uint var secret *C.char defer C.free(unsafe.Pointer(username)) defer C.free(unsafe.Pointer(secret)) errMsg := C.keychain_get(s, &usernameLen, &username, &secretLen, &secret) if errMsg != nil { defer C.free(unsafe.Pointer(errMsg)) goMsg := C.GoString(errMsg) if goMsg == errCredentialsNotFound { return "", "", credentials.NewErrCredentialsNotFound() } return "", "", errors.New(goMsg) } user := C.GoStringN(username, C.int(usernameLen)) pass := C.GoStringN(secret, C.int(secretLen)) return user, pass, nil }
func (match *Match) Captures() map[string][]string { captures := make(map[string][]string) var name, substring *C.char var namelen, sublen C.int C.grok_match_walk_init(&match.gm) for C.grok_match_walk_next(&match.gm, &name, &namelen, &substring, &sublen) == GROK_OK { var substrings []string gname := C.GoStringN(name, namelen) gsubstring := C.GoStringN(substring, sublen) if val := captures[gname]; val == nil { substrings = make([]string, 0) } else { substrings = val } captures[gname] = append(substrings, gsubstring) } C.grok_match_walk_end(&match.gm) return captures }
func (grok *Grok) Match(str string) (map[string]string, error) { var gm C.grok_match_t //log.Print("Attemping to match '", str, "'") grok.lock.Lock() ret := C.grok_exec(grok.grok, C.CString(str), &gm) grok.lock.Unlock() if ret != C.GROK_OK { return nil, GrokError{ret} } var pdata, pname *C.char var pname_len, pdata_len C.int result := make(map[string]string) grok.lock.Lock() C.grok_match_walk_init(&gm) for C.grok_match_walk_next(&gm, &pname, &pname_len, &pdata, &pdata_len) == 0 { name := C.GoStringN(pname, pname_len) data := C.GoStringN(pdata, pdata_len) result[name] = data } C.grok_match_walk_end(&gm) grok.lock.Unlock() return result, nil //grok_match_t }
func next(cur *C.KCCUR) (key, value string) { pair := C.gokccurget(cur) key = C.GoStringN(pair.key.buf, C.int(pair.key.size)) if pair.value.buf != nil { value = C.GoStringN(pair.value.buf, C.int(pair.value.size)) } return }
func (c ResultColumn) make_buffer(s *Statement, addr interface{}) (buffer string) { switch addr := addr.(type) { case *C.uchar: buffer = C.GoStringN((*C.char)(unsafe.Pointer(addr)), C.int(c.ByteCount(s))) case unsafe.Pointer: buffer = C.GoStringN((*C.char)(addr), C.int(c.ByteCount(s))) } return }
// 查询接口(按primary key查) func searchByPrimaryKey(table *Table, primary_key string, need_index int, need_data int) (error, []Index, []string) { var c_request C.mdt_search_request_t var c_response C.mdt_search_response_t // convert request c_request.primary_key.data = C.CString(primary_key) c_request.primary_key.size = C.size_t(len(primary_key)) c_request.need_index = C.int(need_index) c_request.need_data = C.int(need_data) // invoke C api C.mdt_search(table.rep, &c_request, &c_response, nil, nil) // convert result & free result memory err := Ok var data_list []string var index_list []Index c_result_list := (*[1 << 30]C.mdt_search_result_t)(unsafe.Pointer(c_response.result_list)) if c_response.result_list_len == C.size_t(1) { c_result := &c_result_list[0] C.free(unsafe.Pointer(c_result.primary_key.data)) c_index_list := (*[1 << 30]C.mdt_index_t)(unsafe.Pointer(c_result.index_list)) for j := C.size_t(0); j < c_result.index_list_len; j++ { index := &Index{} index.IndexName = C.GoStringN(c_index_list[j].index_name.data, C.int(c_index_list[j].index_name.size)) index.IndexKey = C.GoStringN(c_index_list[j].index_key.data, C.int(c_index_list[j].index_key.size)) index_list = append(index_list, *index) C.free(unsafe.Pointer(c_index_list[j].index_name.data)) C.free(unsafe.Pointer(c_index_list[j].index_key.data)) } C.free(unsafe.Pointer(c_result.index_list)) c_data_list := (*[1 << 30]C.mdt_slice_t)(unsafe.Pointer(c_result.data_list)) for j := C.size_t(0); j < c_result.data_list_len; j++ { data_list = append(data_list, C.GoStringN(c_data_list[j].data, C.int(c_data_list[j].size))) C.free(unsafe.Pointer(c_data_list[j].data)) } C.free(unsafe.Pointer(c_result.data_list)) } else { err = NotFound } C.free(unsafe.Pointer(c_response.result_list)) // free request memory C.free(unsafe.Pointer(c_request.primary_key.data)) return GetError(err), index_list, data_list }
//export onHeader func onHeader(fr *C.nghttp2_frame, name *C.uint8_t, namelen C.size_t, value *C.uint8_t, valuelen C.size_t, flags C.uint8_t, ptr unsafe.Pointer) C.int { if frameType(fr) != C.NGHTTP2_HEADERS { return 0 } f := (*C.nghttp2_headers)((unsafe.Pointer)(fr)) if f.cat != C.NGHTTP2_HCAT_REQUEST { return 0 } id := (int32)(f.hd.stream_id) s := (*session)(ptr) st, ok := s.sc.streams[id] if !ok { return 0 } if st.rw != nil { return 0 } k := C.GoStringN((*C.char)((unsafe.Pointer)(name)), (C.int)(namelen)) v := C.GoStringN((*C.char)((unsafe.Pointer)(value)), (C.int)(valuelen)) v = strings.TrimSpace(v) if k[0] == ':' { switch k { case ":authority": st.authority = v case ":method": st.method = v case ":path": st.path = v case ":scheme": st.scheme = v } } else { st.header.Add(k, v) } st.headerSize += len(k) + len(v) if st.headerSize > maxHeaderSize { s.sc.handleError(st, 431) return 0 } return 0 }
// Read reads a series of bytes from the stream. This method may block the // calling application for an arbitrary amount of time. // Errors are not guaranteed to be reported synchronously with the call, but may // instead be delayed until a subsequent call. // This function is equivalent to the libvirt function "Recv" but it has been // renamed to "Read" in order to implement the standard interface io.Reader. And // due to that interface requirement, this function now returns (0, io.EOF) // instead of (0, nil) when there's nothing left to be read from the stream. func (str Stream) Read(data []byte) (int, error) { dataLen := len(data) cData := (*C.char)(C.malloc(C.size_t(dataLen))) defer C.free(unsafe.Pointer(cData)) str.log.Printf("receiving %v bytes from stream...\n", dataLen) cRet := C.virStreamRecv(str.virStream, (*C.char)(unsafe.Pointer(cData)), C.size_t(dataLen)) ret := int32(cRet) if ret < 0 { err := LastError() str.log.Printf("an error occurred: %v\n", err) return 0, err } str.log.Printf("%v bytes received\n", ret) if ret == 0 && dataLen > 0 { return 0, io.EOF } newData := C.GoStringN(cData, cRet) copy(data, newData) return int(ret), nil }
func createInterface(ifName string) (createdIFName string, file *os.File, err error) { file = nil err = errorNotDeviceFound var readBufLen C.int = 20 var readBuf = C.CString(" ") defer C.free(unsafe.Pointer(readBuf)) for utunnum := 0; utunnum < 255; utunnum++ { conn := kernctl.NewConnByName(utunControlName) conn.UnitId = uint32(utunnum + 1) conn.Connect() _, _, gserr := syscall.Syscall6(syscall.SYS_GETSOCKOPT, uintptr(conn.Fd), uintptr(kernctl.SYSPROTO_CONTROL), uintptr(utunOptIfName), uintptr(unsafe.Pointer(readBuf)), uintptr(unsafe.Pointer(&readBufLen)), 0) if gserr != 0 { continue } else { createdIFName := C.GoStringN(readBuf, C.int(readBufLen)) fmt.Printf("Try num: %d\n", utunnum) fmt.Printf("Fd: %d\n", conn.Fd) fmt.Printf("Dev name: %s [%d]\n", createdIFName, readBufLen) file = os.NewFile(uintptr(conn.Fd), createdIFName) err = nil break } } return createdIFName, file, err }
// MonCommand sends a command to one of the monitors func (c *Conn) MonCommand(args []byte) (buffer []byte, info string, err error) { argv := C.CString(string(args)) defer C.free(unsafe.Pointer(argv)) var ( outs, outbuf *C.char outslen, outbuflen C.size_t ) inbuf := C.CString("") defer C.free(unsafe.Pointer(inbuf)) ret := C.rados_mon_command(c.cluster, &argv, 1, inbuf, // bulk input (e.g. crush map) C.size_t(0), // length inbuf &outbuf, // buffer &outbuflen, // buffer length &outs, // status string &outslen) if outslen > 0 { info = C.GoStringN(outs, C.int(outslen)) C.free(unsafe.Pointer(outs)) } if outbuflen > 0 { buffer = C.GoBytes(unsafe.Pointer(outbuf), C.int(outbuflen)) C.free(unsafe.Pointer(outbuf)) } if ret != 0 { err = RadosError(int(ret)) return nil, info, err } return }
// FindGenericPassword finds the first generic password item which matches the // attributes you provide. Most attributes are optional; you should pass only as // many as you need to narrow the search sufficiently for your application's // intended use. func FindGenericPassword(service, account string) (string, error) { if service == "" || account == "" { return "", errors.New("service and account are required") } cService := C.CString(service) defer C.free(unsafe.Pointer(cService)) cAccount := C.CString(account) defer C.free(unsafe.Pointer(cAccount)) cPasswordLen := C.UInt32(0) cPassword := unsafe.Pointer(nil) errCode := C.SecKeychainFindGenericPassword( nil, // default keychain C.UInt32(C.strlen(cService)), cService, C.UInt32(C.strlen(cAccount)), cAccount, &cPasswordLen, &cPassword, nil, ) if err := newKeychainError(errCode); err != nil { return "", err } defer C.SecKeychainItemFreeContent(nil, cPassword) return C.GoStringN((*C.char)(cPassword), C.int(cPasswordLen)), nil }
// GetW works like Get but also returns a channel that will receive // a single Event value when the data or existence of the given ZooKeeper // node changes or when critical session events happen. See the // documentation of the Event type for more details. func (conn *Conn) GetW(path string) (data string, stat *Stat, watch <-chan Event, err error) { conn.mutex.RLock() defer conn.mutex.RUnlock() if conn.handle == nil { return "", nil, nil, closingError("getw", path) } cpath := C.CString(path) cbuffer := (*C.char)(C.malloc(bufferSize)) cbufferLen := C.int(bufferSize) defer C.free(unsafe.Pointer(cpath)) defer C.free(unsafe.Pointer(cbuffer)) watchId, watchChannel := conn.createWatch(true) var cstat Stat rc, cerr := C.zoo_wget(conn.handle, cpath, C.watch_handler, unsafe.Pointer(watchId), cbuffer, &cbufferLen, &cstat.c) if rc != C.ZOK { conn.forgetWatch(watchId) return "", nil, nil, zkError(rc, cerr, "getw", path) } if cbufferLen != -1 { data = C.GoStringN(cbuffer, cbufferLen) } return data, &cstat, watchChannel, nil }
func (d *stringDecoder) decode(ptr reflect.Value, shape []int64) error { if len(shape) == 0 { var offset uint64 if err := binary.Read(d.offsets, nativeEndian, &offset); err != nil { return err } var ( src = (*C.char)(unsafe.Pointer(&d.data[offset])) srcLen = C.size_t(len(d.data)) - C.size_t(offset) dst *C.char dstLen C.size_t ) if offset > uint64(len(d.data)) { return fmt.Errorf("invalid offsets in String Tensor") } C.TF_StringDecode(src, srcLen, &dst, &dstLen, d.status.c) if err := d.status.Err(); err != nil { return err } s := ptr.Interface().(*string) *s = C.GoStringN(dst, C.int(dstLen)) return nil } val := reflect.Indirect(ptr) val.Set(reflect.MakeSlice(typeOf(String, shape), int(shape[0]), int(shape[0]))) for i := 0; i < val.Len(); i++ { if err := d.decode(val.Index(i).Addr(), shape[1:]); err != nil { return err } } return nil }
func pyObjToInterface(o *C.PyObject) interface{} { if C.myPyString_Check(o) != 0 { return C.GoStringN(C.PyString_AsString(o), C.int(C.PyString_Size(o))) } else if C.myPyInt_Check(o) != 0 { return int64(C.PyInt_AsLong(o)) } else if C.myPyDict_Check(o) != 0 { v := make(map[interface{}]interface{}) items := C.PyDict_Items(o) for i := 0; i < int(C.PyTuple_Size(items)); i++ { item := C.PyTuple_GetItem(items, C.Py_ssize_t(i)) key := C.PyTuple_GetItem(item, 0) value := C.PyTuple_GetItem(item, 1) v[pyObjToInterface(key)] = pyObjToInterface(value) } C.Py_DecRef(items) return v } else if C.myPyTuple_Check(o) != 0 { length := int(C.PyTuple_Size(o)) list := make([]interface{}, length) for i := 0; i < length; i++ { list[i] = pyObjToInterface(C.PyTuple_GetItem(o, C.Py_ssize_t(i))) } return list } return nil }
func (evt *Event) ToStruct(data interface{}) interface{} { t := reflect.TypeOf(data) struct_field_ids := make([]uint64, 0) tdb_field_ids := make([]uint64, 0) for i := 0; i < t.NumField(); i++ { field := t.Field(i) field_name := field.Tag.Get("tdb") if field_name != "" { tdb_id := evt.trail.db.fieldNameToId[field_name] struct_field_ids = append(struct_field_ids, uint64(i)) tdb_field_ids = append(tdb_field_ids, tdb_id) } } v := reflect.New(t) v.Elem().Field(0).SetInt(int64(evt.Timestamp)) for k := 1; k < len(tdb_field_ids); k++ { var vlength C.uint64_t itemValue := C.tdb_get_item_value(evt.trail.db.db, evt.items[tdb_field_ids[k]-1], &vlength) value := C.GoStringN(itemValue, C.int(vlength)) v.Elem().Field(int(struct_field_ids[k])).SetString(value) } return v }
func (c Chip) String() string { var buffer [200]C.char len := C.sensors_snprintf_chip_name(&buffer[0], C.size_t(len(buffer)), c.chip) return C.GoStringN(&buffer[0], len) }
//export go_find_callback func go_find_callback(result *C.struct_go_find_result, key uint64) { context, err := Pool.Get(key) if err != nil { panic("Unable to find find callback") } callback := context.(func(*findResult)) var indexEntries []C.struct_c_index_entry size := int(result.entries_count) sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&indexEntries))) sliceHeader.Cap = size sliceHeader.Len = size sliceHeader.Data = uintptr(unsafe.Pointer(result.entries)) var IndexDatas []IndexEntry for _, item := range indexEntries { IndexDatas = append(IndexDatas, IndexEntry{ Data: C.GoStringN(item.data, C.int(item.size)), }) } callback(&findResult{ id: *result.id, data: IndexDatas, err: nil, }) }
func (z *zset) Range(r1, r2 int) []string { if r1 < 1 { r1 = 1 } if r2 < 1 { r2 = 1 } var reverse, rangelen int if r1 <= r2 { reverse = 0 rangelen = r2 - r1 + 1 } else { reverse = 1 rangelen = r1 - r2 + 1 } node := C.slGetNodeByRank(z.sl, C.ulong(r1)) result := make([]string, 0, rangelen) rr := C.int(reverse) for n := 0; node != nil && n < rangelen; { result = append(result, C.GoStringN(node.obj.ptr, C.int(node.obj.length))) node = C.getNextNode(node, rr) n++ } return result }
func (z *zset) RangeByScore(s1, s2 float64) []string { var reverse int var node *C.skiplistNode cs1, cs2 := C.double(s1), C.double(s2) if s1 <= s2 { reverse = 0 node = C.slFirstInRange(z.sl, cs1, cs2) } else { reverse = 1 node = C.slLastInRange(z.sl, cs2, cs1) } result := make([]string, 0) rr := C.int(reverse) for node != nil { if reverse == 1 { if node.score < cs2 { break } } else { if node.score > cs2 { break } } result = append(result, C.GoStringN(node.obj.ptr, C.int(node.obj.length))) node = C.getNextNode(node, rr) } return result }
// unpackDataValue converts a value shipped by C++ into a native Go value. // // HEADS UP: This is considered safe to be run out of the main GUI thread. // If that changes, fix the call sites. func unpackDataValue(dvalue *C.DataValue, engine *Engine) interface{} { datap := unsafe.Pointer(&dvalue.data) switch dvalue.dataType { case C.DTString: s := C.GoStringN(*(**C.char)(datap), dvalue.len) // TODO If we move all unpackDataValue calls to the GUI thread, // can we get rid of this allocation somehow? C.free(unsafe.Pointer(*(**C.char)(datap))) return s case C.DTBool: return *(*bool)(datap) case C.DTInt64: return *(*int64)(datap) case C.DTInt32: return *(*int32)(datap) case C.DTFloat64: return *(*float64)(datap) case C.DTFloat32: return *(*float32)(datap) case C.DTGoAddr: return (*(**valueFold)(datap)).gvalue case C.DTInvalid: return nil case C.DTObject: return &Object{ engine: engine, addr: (*(*unsafe.Pointer)(datap)), } } panic(fmt.Sprintf("unsupported data type: %d", dvalue.dataType)) }
// Copy returns a Go-managed copy of s. func (s RawString) Copy() string { if s == "" { return "" } h := (*reflect.StringHeader)(unsafe.Pointer(&s)) return C.GoStringN((*C.char)(unsafe.Pointer(h.Data)), C.int(h.Len)) }
//export onAppendGoCb func onAppendGoCb(round C.uint64_t, str *C.char, length C.int, p unsafe.Pointer) { i := *(*int)(p) registeredNodesLock.RLock() defer registeredNodesLock.RUnlock() node := registeredNodes[i] node.callbackHandler.OnAppend(node, uint64(round), C.GoStringN(str, length)) }
func (pd pnDecoder) unmarshalString(v *string) error { pnBytes, err := pd.unmarshalPnBytes("string") if err == nil { *v = C.GoStringN(pnBytes.start, C.int(pnBytes.size)) } return err }
// Copy returns a Go-managed copy of raw string. func (raw RawString) Copy() string { if len(raw) == 0 { return "" } h := (*stringHeader)(unsafe.Pointer(&raw)) return C.GoStringN((*C.char)(unsafe.Pointer(h.Data)), C.int(h.Len)) }
func (stmt *Stmt) Query(args []driver.Value) (driver.Rows, error) { var err error c := stmt.c if c.db == nil { return nil, errClosed } if err = stmt.bind(args); err != nil { return nil, fmt.Errorf("bind: %s", err) } rows := &Rows{c: c} var columnCount C.int if C.nuodb_statement_query(c.db, stmt.st, &rows.rs, &columnCount) != 0 { return nil, c.lastError() } if columnCount > 0 { cc := int(columnCount) rows.rowValues = make([]C.struct_nuodb_value, cc) if C.nuodb_resultset_column_names(c.db, rows.rs, (*C.struct_nuodb_value)(unsafe.Pointer(&rows.rowValues[0]))) != 0 { return nil, c.lastError() } rows.columnNames = make([]string, cc) for i, value := range rows.rowValues { if length := (C.int)(value.i32); length > 0 { cstr := (*C.char)(unsafe.Pointer(uintptr(value.i64))) rows.columnNames[i] = C.GoStringN(cstr, length) } } } return rows, nil }
func (pd pnDecoder) unmarshalSymbol(v *Symbol) error { pnBytes, err := pd.unmarshalPnBytes("symbol") if err == nil { *v = Symbol(C.GoStringN(pnBytes.start, C.int(pnBytes.size))) } return err }
func (i *INFO) String() string { kstr := C.kstring_t{} C.format_info(i.b, i.hdr, &kstr) v := C.GoStringN(kstr.s, C.int(kstr.l)) C.free(unsafe.Pointer(kstr.s)) return v }
// Version will return a map reflecting versions of each memcached server func (client *Client) Version() (map[string]string, error) { client.lock() defer client.unlock() var rst *C.broadcast_result_t var n C.size_t rv := make(map[string]string) errCode := C.client_version(client._imp, &rst, &n) defer C.client_destroy_broadcast_result(client._imp) sr := unsafe.Sizeof(*rst) for i := 0; i < int(n); i++ { if rst.lines == nil || rst.line_lens == nil { continue } host := C.GoString(rst.host) version := C.GoStringN(*rst.lines, C.int(*rst.line_lens)) rv[host] = version rst = (*C.broadcast_result_t)(unsafe.Pointer(uintptr(unsafe.Pointer(rst)) + sr)) } if errCode != 0 { return rv, networkError(errorMessage[errCode]) } return rv, nil }
// At takes a region like 1:45678-56789 and returns a channel on which // it sends a string for each line that falls in that interval. func (t *Tabix) At(region string) interfaces.RelatableChannel { cs := C.CString(region) defer C.free(unsafe.Pointer(cs)) out := make(interfaces.RelatableChannel, 20) itr := C.tabix_itr_querys(t.tbx, cs) go func() { kstr := C.kstring_t{} l := C.int(10) for l > 0 { l := C.atbx_itr_next(t.htf, t.tbx, itr, &kstr) if l < 0 { break } //res := C.GoString(kstr.s) b := C.bcf_init() ret := C.vcf_parse(&kstr, t.hdr, b) if ret < 0 { log.Printf("error parsing %s\n", C.GoStringN(kstr.s, C.int(kstr.l))) } out <- NewVariant(b, t.hdr, 1) } close(out) C.hts_itr_destroy(itr) C.free(unsafe.Pointer(kstr.s)) }() return out }