func NewField(height int, width int, top int, left int, offscreen int, nbuf int) (*Field, error) { field := (*Field)(C.new_field(C.int(height), C.int(width), C.int(top), C.int(left), C.int(offscreen), C.int(nbuf))) if field == nil { return nil, FormsError{"NewField failed"} } return field, nil }
// 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 }
func (c *Code) getDecode(errList []byte, cache bool) (node *decodeNode) { if cache { node = c.decode.getDecode(errList, 0, byte(c.M)) } else { node = newDecodeNode(errList, byte(c.M)) } node.mutex.Lock() defer node.mutex.Unlock() if node.galoisTables == nil || node.decodeIndex == nil { node.galoisTables = make([]byte, c.K*c.M*32) node.decodeIndex = make([]byte, c.K) decodeMatrix := make([]byte, c.M*c.K) srcInErr := make([]byte, c.M) nErrs := len(errList) nSrcErrs := 0 for _, err := range errList { srcInErr[err] = 1 if int(err) < c.K { nSrcErrs++ } } C.gf_gen_decode_matrix((*C.uchar)(&c.EncodeMatrix[0]), (*C.uchar)(&decodeMatrix[0]), (*C.uchar)(&node.decodeIndex[0]), (*C.uchar)(&errList[0]), (*C.uchar)(&srcInErr[0]), C.int(nErrs), C.int(nSrcErrs), C.int(c.K), C.int(c.M)) C.ec_init_tables(C.int(c.K), C.int(nErrs), (*C.uchar)(&decodeMatrix[0]), (*C.uchar)(&node.galoisTables[0])) } return node }
// Sets the debugging hook function. // // Argument fn is the hook function. mask specifies on which events the hook // will be called: it is formed by a bitwise OR of the constants Maskcall, // Maskret, Maskline, and Maskcount. The count argument is only meaningful // when the mask includes Maskcount. The hook is called for each event type // present in mask. // // A hook is disabled by setting mask to 0. func (s *State) Sethook(fn Hook, mask, count int) error { s.Getglobal(namehooks) if mask&Maskcall == Maskcall { s.Pushstring(namecall) s.Pushlightuserdata(unsafe.Pointer(&fn)) s.Settable(-3) } if mask&Maskret == Maskret { s.Pushstring(nameret) s.Pushlightuserdata(unsafe.Pointer(&fn)) s.Settable(-3) } if mask&Maskline == Maskline { s.Pushstring(nameline) s.Pushlightuserdata(unsafe.Pointer(&fn)) s.Settable(-3) } if mask&Maskcount == Maskcount { s.Pushstring(namecount) s.Pushlightuserdata(unsafe.Pointer(&fn)) s.Settable(-3) } s.Pop(1) // pop hook table C.sethook(s.l, C.int(mask), C.int(count)) return nil }
//recovers the public key from the signature //recovery of pubkey means correct signature func RecoverPubkey(msg []byte, sig []byte) []byte { if len(sig) != 65 { log.Panic() } var pubkey []byte = make([]byte, 33) var msg_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&msg[0])) var sig_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sig[0])) var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0])) var pubkeylen C.int ret := C.secp256k1_ecdsa_recover_compact( msg_ptr, C.int(len(msg)), sig_ptr, pubkey_ptr, &pubkeylen, C.int(1), C.int(sig[64]), ) if ret == 0 || int(pubkeylen) != 33 { return nil } return pubkey }
func NewMat(r, c int) Mat { var m Mat m.mat = C.NewGOMat(C.int(r), C.int(c)) //m.Row() = r //m.Colunm() = c return m }
func (t *Sound) Play(loops int) { t.channel = int(C.Mix_PlayChannelTimed(C.int(-1), t.chunk, C.int(loops), C.int(-1))) if t.channel == -1 { panic(fmt.Sprintf("Unable to play Sound file (%v): %v", t.name, util.GetMixError())) } t.SetVolume(GDefaultVolume) }
// MONGO_EXPORT int mongo_update( mongo *conn, const char *ns, const bson *cond, // const bson *op, int flags, mongo_write_concern *custom_write_concern ); func (m *Mongo) Update(ns string, cond, op *Bson, flags int, writeConcern *MongoWriteConcern) int { if writeConcern == nil { return int(C.mongo_update(m.conn, C.CString(ns), cond._bson, op._bson, C.int(flags), nil)) } return int(C.mongo_update(m.conn, C.CString(ns), cond._bson, op._bson, C.int(flags), writeConcern.writeConcern)) }
func (re *Regexp) find(b []byte, n int, offset int) (match []int) { if n == 0 { b = []byte{0} } ptr := unsafe.Pointer(&b[0]) matchData := re.matchData capturesPtr := unsafe.Pointer(&(matchData.indexes[matchData.count][0])) numCaptures := int32(0) numCapturesPtr := unsafe.Pointer(&numCaptures) pos := int(C.SearchOnigRegex((ptr), C.int(n), C.int(offset), C.int(ONIG_OPTION_DEFAULT), re.regex, re.region, re.errorInfo, (*C.char)(nil), (*C.int)(capturesPtr), (*C.int)(numCapturesPtr))) if pos >= 0 { if numCaptures <= 0 { panic("cannot have 0 captures when processing a match") } match2 := matchData.indexes[matchData.count][:numCaptures*2] match = make([]int, len(match2)) for i := range match2 { match[i] = int(match2[i]) } numCapturesInPattern := int32(C.onig_number_of_captures(re.regex)) + 1 if numCapturesInPattern != numCaptures { log.Fatalf("expected %d captures but got %d\n", numCapturesInPattern, numCaptures) } } return }
func Parse(content, inEncoding, url []byte, options int, outEncoding []byte) (doc *XmlDocument, err error) { inEncoding = AppendCStringTerminator(inEncoding) outEncoding = AppendCStringTerminator(outEncoding) var docPtr *C.xmlDoc contentLen := len(content) if contentLen > 0 { var contentPtr, urlPtr, encodingPtr unsafe.Pointer contentPtr = unsafe.Pointer(&content[0]) if len(url) > 0 { url = AppendCStringTerminator(url) urlPtr = unsafe.Pointer(&url[0]) } if len(inEncoding) > 0 { encodingPtr = unsafe.Pointer(&inEncoding[0]) } docPtr = C.xmlParse(contentPtr, C.int(contentLen), urlPtr, encodingPtr, C.int(options), nil, 0) if docPtr == nil { err = ERR_FAILED_TO_PARSE_XML } else { doc = NewDocument(unsafe.Pointer(docPtr), contentLen, inEncoding, outEncoding) } } else { doc = CreateEmptyDocument(inEncoding, outEncoding) } return }
// Emit is a wrapper around g_signal_emitv() and emits the signal // specified by the string s to an Object. Arguments to callback // functions connected to this signal must be specified in args. Emit() // returns an interface{} which must be type asserted as the Go // equivalent type to the return value for native C callback. // // Note that this code is unsafe in that the types of values in args are // not checked against whether they are suitable for the callback. func (v *Object) Emit(s string, args ...interface{}) (interface{}, error) { cstr := C.CString(s) defer C.free(unsafe.Pointer(cstr)) // Create array of this instance and arguments valv := C.alloc_gvalue_list(C.int(len(args)) + 1) defer C.free(unsafe.Pointer(valv)) // Add args and valv val, err := GValue(v) if err != nil { return nil, errors.New("Error converting Object to GValue: " + err.Error()) } C.val_list_insert(valv, C.int(0), val.native()) for i := range args { val, err := GValue(args[i]) if err != nil { return nil, fmt.Errorf("Error converting arg %d to GValue: %s", i, err.Error()) } C.val_list_insert(valv, C.int(i+1), val.native()) } t := v.TypeFromInstance() // TODO: use just the signal name id := C.g_signal_lookup((*C.gchar)(cstr), C.GType(t)) ret, err := ValueAlloc() if err != nil { return nil, errors.New("Error creating Value for return value") } C.g_signal_emitv(valv, id, C.GQuark(0), ret.native()) return ret.GoValue() }
// Sets the value of a closure's upvalue. It assigns the value at the top // of the stack to the upvalue and returns its name. It also pops the value // from the stack. Parameters funcindex and n are as in the Getupvalue. // // Returns an error (and pops nothing) when the index is greater // than the number of upvalues. func (this *State) Setupvalue(funcindex, n int) (string, error) { r := C.lua_setupvalue(this.luastate, C.int(funcindex), C.int(n)) if r == nil { return "", errors.New("index exceeds number of upvalues") } return C.GoString(r), nil }
func (field *Field) Link(top int, left int) (*Field, error) { link := (*Field)(C.link_field((*C.FIELD)(field), C.int(top), C.int(left))) if link == nil { return nil, FormsError{"Field.Link failed"} } return link, nil }
func (field *Field) DupField(top int, left int) (*Field, error) { dup := (*Field)(C.dup_field((*C.FIELD)(field), C.int(top), C.int(left))) if dup == nil { return nil, FormsError{"Field.Dup failed"} } return dup, nil }
// The C side of things will still need to allocate memory, due to the slices. // Assumes Configuration is valid. func (config *Configuration) _CGO() *C.CGO_Configuration { INFO.Println("Converting Config: ", config) size := C.size_t(unsafe.Sizeof(C.CGO_Configuration{})) c := (*C.CGO_Configuration)(C.malloc(size)) // Need to convert each IceServer struct individually. total := len(config.IceServers) if total > 0 { sizeof := unsafe.Sizeof(C.CGO_IceServer{}) cServers := unsafe.Pointer(C.malloc(C.size_t(sizeof * uintptr(total)))) ptr := uintptr(cServers) for _, server := range config.IceServers { *(*C.CGO_IceServer)(unsafe.Pointer(ptr)) = server._CGO() ptr += sizeof } c.iceServers = (*C.CGO_IceServer)(cServers) } c.numIceServers = C.int(total) // c.iceServers = (*C.CGO_IceServer)(unsafe.Pointer(&config.IceServers)) c.iceTransportPolicy = C.int(config.IceTransportPolicy) c.bundlePolicy = C.int(config.BundlePolicy) // [ED] c.RtcpMuxPolicy = C.int(config.RtcpMuxPolicy) c.peerIdentity = C.CString(config.PeerIdentity) // [ED] c.Certificates = config.Certificates // [ED] c.IceCandidatePoolSize = C.int(config.IceCandidatePoolSize) return c }
func (self *Device) BulkRead(ep int, dat []byte) int { return int(C.usb_bulk_read(self.handle, C.int(ep), (*C.char)(unsafe.Pointer(&dat[0])), C.int(len(dat)), C.int(self.timeout))) }
// Full customization of the call. Arguments essentially map to UI_UTIL_read_pw_string func GetPassWithOptions(prompt string, confirm, max int) (pw string, e error) { pw = "" e = nil if max <= 0 { e = errors.New("Invalid argument: maximum password length") return pw, e } if len(prompt) <= 0 { e = errors.New("Invalid argument: prompt") return pw, e } sz := C.int(max) buf := C.malloc(C.size_t(sz)) bptr := (*C.char)(buf) p := C.CString(prompt) rc, err := C.UI_UTIL_read_pw_string(bptr, sz, p, C.int(confirm)) if rc != 0 { e = err } else { pw = C.GoString(bptr) } C.free(buf) return pw, e }
func sqlOpen(name string, flags int, vfs string) (conn *sqlConnection, rc int) { conn = new(sqlConnection) p := C.CString(name) if len(vfs) > 0 { q := C.CString(vfs) rc = int(C.sqlite3_open_v2(p, &conn.handle, C.int(flags), q)) C.free(unsafe.Pointer(q)) } else { rc = int(C.sqlite3_open_v2(p, &conn.handle, C.int(flags), nil)) } C.free(unsafe.Pointer(p)) // We could get a handle even if there's an error, see // http://www.sqlite.org/c3ref/open.html for details. // Initially we didn't want to return a connection on // error, but we actually have to since we want to fill // in a SystemError struct. Sigh. // if rc != StatusOk && conn.handle != nil { // _ = conn.sqlClose(); // conn = nil; // } return }
//export get_route_family func get_route_family(input *C.char) C.int { rf, err := bgp.GetRouteFamily(C.GoString(input)) if err != nil { return C.int(-1) } return C.int(rf) }
func SetVideoMode(width int, height int, bpp int, flags int) { screen := C.SDL_SetVideoMode(C.int(width), C.int(height), C.int(bpp), C.Uint32(flags)) if screen == nil { panic("unable to set video mode") } }
func (t *Sound) FadeIn(duration Double, loops int) { t.channel = int(C.Mix_FadeInChannelTimed(C.int(-1), t.chunk, C.int(loops), C.int(duration*1000.0), C.int(-1))) if t.channel == -1 { panic(fmt.Sprintf("Unable to FadeIn Sound file (%v): %v", t.name, util.GetMixError())) } t.SetVolume(GDefaultVolume) }
func Get_result_info(req_handle int) ([]GCI_COL_INFO, GCI_CUBRID_STMT, int) { var handle C.int = C.int(req_handle) var c_col_info *C.T_CCI_COL_INFO var go_col_info []C.T_CCI_COL_INFO var cubrid_stmt C.T_CCI_CUBRID_STMT var col_count C.int var gci_col_info []GCI_COL_INFO var gci_cubrid_stmt GCI_CUBRID_STMT c_col_info = C.cci_get_result_info(handle, &cubrid_stmt, &col_count) gci_cubrid_stmt = GCI_CUBRID_STMT(cubrid_stmt) sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&go_col_info))) sliceHeader.Cap = int(col_count) sliceHeader.Len = int(col_count) sliceHeader.Data = uintptr(unsafe.Pointer(c_col_info)) gci_col_info = make([]GCI_COL_INFO, int(col_count)) for i := 0; i < int(col_count); i++ { gci_col_info[i].u_type = GCI_U_TYPE(go_col_info[C.int(i)]._type) gci_col_info[i].is_non_null = C.GoString(&go_col_info[C.int(i)].is_non_null) gci_col_info[i].scale = int16(go_col_info[C.int(i)].scale) gci_col_info[i].precision = int(go_col_info[C.int(i)].precision) } return gci_col_info, gci_cubrid_stmt, int(col_count) }
//generate signature in repeatable way func SignDeterministic(msg []byte, seckey []byte, nonce_seed []byte) []byte { nonce := SumSHA256(nonce_seed) //deterministicly generate nonce var sig []byte = make([]byte, 65) var recid C.int var msg_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&msg[0])) var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0])) var nonce_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&nonce[0])) var sig_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sig[0])) if C.secp256k1_ecdsa_seckey_verify(seckey_ptr) != C.int(1) { log.Panic("Invalid secret key") } ret := C.secp256k1_ecdsa_sign_compact( msg_ptr, C.int(len(msg)), sig_ptr, seckey_ptr, nonce_ptr, &recid) sig[64] = byte(int(recid)) if int(recid) > 4 { log.Panic() } if ret != 1 { return SignDeterministic(msg, seckey, nonce_seed) //nonce invalid,retry } return sig }
// OpenDead creates a Pcap handle without having it attached to a device // or to a file. It is typically used when just using the pcap package // for compiling BPF code. func OpenDead(linktype layers.LinkType, snaplen int32) (handle *Handle, _ error) { cptr := C.pcap_open_dead(C.int(linktype), C.int(snaplen)) if cptr == nil { return nil, errors.New("pcap_open_dead failed") } return &Handle{cptr: cptr}, nil }
func (s *driverStmt) exec(params []driver.Value) *C.PGresult { stmtName := C.CString(s.name) defer C.free(unsafe.Pointer(stmtName)) cparams := buildCArgs(params) defer C.freeCharArray(cparams, C.int(len(params))) return C.PQexecPrepared(s.db, stmtName, C.int(len(params)), cparams, nil, nil, 0) }
func (osx *osxSystemObject) CreateWindow(x, y, width, height int) { globalLock.Lock() defer globalLock.Unlock() w := (*unsafe.Pointer)(unsafe.Pointer(&osx.window)) c := (*unsafe.Pointer)(unsafe.Pointer(&osx.context)) C.CreateWindow(w, c, C.int(x), C.int(y), C.int(width), C.int(height)) }
// Data buffer to decode must be of the (M/K)*Size given in the constructor. // The error list must contain M-K values, corresponding to the shards // with errors (eg. [0, 2, 4, 6]). // Cache stores the decode matrices in a trie, enabling a faster decode // with a memory tradeoff. // The returned decoded data is the orignal data of length Size func (c *Code) Decode(encoded []byte, errList []byte, cache bool) (recovered []byte) { if len(encoded) != c.M*c.ShardLength { panic("Data to decode is not the proper size") } if len(errList) > c.M-c.K { panic("Too many errors, cannot decode") } if len(errList) == 0 { recovered = append(recovered, encoded[:c.K*c.ShardLength]...) } else { node := c.getDecode(errList, cache) for i := 0; i < c.K; i++ { recovered = append(recovered, encoded[(int(node.decodeIndex[i])*c.ShardLength):int(node.decodeIndex[i]+1)*c.ShardLength]...) } decoded := make([]byte, c.M*c.ShardLength) C.ec_encode_data(C.int(c.ShardLength), C.int(c.K), C.int(c.M), (*C.uchar)(&node.galoisTables[0]), (*C.uchar)(&recovered[0]), (*C.uchar)(&decoded[0])) copy(recovered, encoded) for i, err := range errList { if int(err) < c.K { copy(recovered[int(err)*c.ShardLength:int(err+1)*c.ShardLength], decoded[i*c.ShardLength:(i+1)*c.ShardLength]) } } } return recovered }
func toFeatureNodes(X *mat64.Dense) []*C.struct_feature_node { featureNodes := []*C.struct_feature_node{} nRows, nCols := X.Dims() for i := 0; i < nRows; i++ { row := []C.struct_feature_node{} for j := 0; j < nCols; j++ { val := X.At(i, j) if val != 0 { row = append(row, C.struct_feature_node{ index: C.int(j + 1), value: C.double(val), }) } } row = append(row, C.struct_feature_node{ index: C.int(-1), value: C.double(0), }) featureNodes = append(featureNodes, &row[0]) } return featureNodes }
// Sets up a video mode with the specified width, height, bits-per-pixel and // returns a corresponding surface. You don't need to call the Free method // of the returned surface, as it will be done automatically by sdl.Quit. func SetVideoMode(w int, h int, bpp int, flags uint32) *Surface { GlobalMutex.Lock() var screen = C.SDL_SetVideoMode(C.int(w), C.int(h), C.int(bpp), C.Uint32(flags)) currentVideoSurface = wrap(screen) GlobalMutex.Unlock() return currentVideoSurface }
// Image places the image in s image at (x,y) with dimensions (w,h) func Image(x, y float64, w, h int, s string) { f, ferr := os.Open(s) if ferr != nil { fakeimage(x, y, w, h, s) return } defer f.Close() img, _, err := image.Decode(f) if err != nil { fakeimage(x, y, w, h, s) return } bounds := img.Bounds() minx := bounds.Min.X maxx := bounds.Max.X miny := bounds.Min.Y maxy := bounds.Max.Y data := make([]C.VGubyte, w*h*4) n := 0 // println("minx", minx, "maxx", maxx, "miny", miny, "maxy", maxy) for y := miny; y < maxy; y++ { for x := minx; x < maxx; x++ { r, g, b, a := img.At(x, (maxy-1)-y).RGBA() // OpenVG has origin at lower left, y increasing up data[n] = C.VGubyte(r) n++ data[n] = C.VGubyte(g) n++ data[n] = C.VGubyte(b) n++ data[n] = C.VGubyte(a) n++ } } C.makeimage(C.VGfloat(x), C.VGfloat(y), C.int(w), C.int(h), &data[0]) }