//export sourceFill func sourceFill(dinfo *C.struct_jpeg_decompress_struct) C.boolean { mgr := getSourceManager(dinfo) buffer := [readBufferSize]byte{} bytes, err := mgr.src.Read(buffer[:]) C.memcpy(mgr.buffer, unsafe.Pointer(&buffer[0]), C.size_t(bytes)) mgr.pub.bytes_in_buffer = C.size_t(bytes) mgr.currentSize = bytes mgr.pub.next_input_byte = (*C.JOCTET)(mgr.buffer) if err == io.EOF { if bytes == 0 { if mgr.startOfFile { releaseSourceManager(mgr) panic("input is empty") } // EOF and need more data. Fill in a fake EOI to get a partial image. footer := []byte{0xff, C.JPEG_EOI} C.memcpy(mgr.buffer, unsafe.Pointer(&footer[0]), C.size_t(len(footer))) mgr.pub.bytes_in_buffer = 2 } } else if err != nil { releaseSourceManager(mgr) panic(err) } mgr.startOfFile = false return C.TRUE }
//export callback_friend_request func callback_friend_request( c_tox *C.Tox, c_public_key *C.uint8_t, c_message *C.uint8_t, c_length C.size_t, c_user_data unsafe.Pointer, ) { // Initialize variables. tox := (*Tox)(c_user_data) var publicKey ToxPublicKey message := make([]byte, c_length) // Copy the public key. C.memcpy( unsafe.Pointer(&publicKey[0]), unsafe.Pointer(c_public_key), ToxPublicKeySize, ) // Copy the friend request message. if c_length > 0 { C.memcpy( unsafe.Pointer(&message[0]), unsafe.Pointer(c_message), c_length, ) } // Register the callback. tox.onFriendRequest(tox, publicKey, message) }
func fill_pdu_for_test_crypt(is_encrypt bool, pt C.enum_snmp_privacy, salt, key, data []byte) ([]byte, error) { var digest [100000]byte var pdu C.snmp_pdu_t C.snmp_pdu_init(&pdu) pdu.user.priv_proto = pt C.memcpy(unsafe.Pointer(&pdu.user.priv_key[0]), unsafe.Pointer(&key[0]), C.size_t(C.SNMP_PRIV_KEY_SIZ)) pdu.user.priv_len = C.size_t(16) //C.size_t(C.SNMP_PRIV_KEY_SIZ) //(au == SNMP_PRIV_DES ) ? SNMP_AUTH_HMACMD5_KEY_SIZ : SNMP_AUTH_HMACSHA_KEY_SIZ; pdu.engine.engine_boots = 3 pdu.engine.engine_time = 3 C.memcpy(unsafe.Pointer(&pdu.msg_salt[0]), unsafe.Pointer(&salt[0]), 8) copy(digest[:], data) pdu.scoped_ptr = (*C.u_char)(unsafe.Pointer(&digest[0])) pdu.scoped_len = C.size_t((len(data) / 8) * 8) var ret_code C.enum_snmp_code if is_encrypt { ret_code = C.snmp_pdu_encrypt(&pdu) } else { ret_code = C.snmp_pdu_decrypt(&pdu) } if 0 != ret_code { err := errors.New(C.GoString(C.snmp_pdu_get_error(&pdu, ret_code))) return nil, err } return readGoBytes((*C.uint8_t)(pdu.scoped_ptr), C.uint32_t(pdu.scoped_len)), nil }
//export ReadMsgpackFrame // // ReadMsgpackFrame reads the msgpack frame at byteOffset in rawStream, decodes the // 2-5 bytes of a msgpack binary array (either bin8, bin16, or bin32), and returns // and the decoded-into-R object and the next byteOffset to use. // func ReadMsgpackFrame(rawStream C.SEXP, byteOffset C.SEXP) C.SEXP { var start int if C.TYPEOF(byteOffset) == C.REALSXP { start = int(C.get_real_elt(byteOffset, 0)) } else if C.TYPEOF(byteOffset) == C.INTSXP { start = int(C.get_int_elt(byteOffset, 0)) } else { C.ReportErrorToR_NoReturn(C.CString("read.msgpack.frame(x, byteOffset) requires byteOffset to be a numeric byte-offset number.")) } // rawStream must be a RAWSXP if C.TYPEOF(rawStream) != C.RAWSXP { C.ReportErrorToR_NoReturn(C.CString("read.msgpack.frame(x, byteOffset) requires x be a RAW vector of bytes.")) } n := int(C.Rf_xlength(rawStream)) if n == 0 { return C.R_NilValue } if start >= n { C.ReportErrorToR_NoReturn(C.CString(fmt.Sprintf("read.msgpack.frame(x, byteOffset) error: byteOffset(%d) is beyond the length of x (x has len %d).", start, n))) } var decoder [5]byte C.memcpy(unsafe.Pointer(&decoder[0]), unsafe.Pointer(C.get_raw_elt_ptr(rawStream, C.ulonglong(start))), C.size_t(5)) headerSz, _, totalSz, err := DecodeMsgpackBinArrayHeader(decoder[:]) if err != nil { C.ReportErrorToR_NoReturn(C.CString(fmt.Sprintf("ReadMsgpackFrame error trying to decode msgpack frame: %s", err))) } if start+totalSz > n { C.ReportErrorToR_NoReturn(C.CString(fmt.Sprintf("read.msgpack.frame(x, byteOffset) error: byteOffset(%d) plus the frames size(%d) goes beyond the length of x (x has len %d).", start, totalSz, n))) } bytes := make([]byte, totalSz) C.memcpy(unsafe.Pointer(&bytes[0]), unsafe.Pointer(C.get_raw_elt_ptr(rawStream, C.ulonglong(start))), C.size_t(totalSz)) rObject := decodeMsgpackToR(bytes[headerSz:]) C.Rf_protect(rObject) returnList := C.allocVector(C.VECSXP, C.R_xlen_t(2)) C.Rf_protect(returnList) C.SET_VECTOR_ELT(returnList, C.R_xlen_t(0), C.Rf_ScalarReal(C.double(float64(start+totalSz)))) C.SET_VECTOR_ELT(returnList, C.R_xlen_t(1), rObject) C.Rf_unprotect_ptr(rObject) C.Rf_unprotect_ptr(returnList) return returnList }
/* Receive a message part from a socket. For a description of flags, see: http://api.zeromq.org/2-2:zmq-recv#toc2 */ func (soc *Socket) RecvBytes(flags Flag) ([]byte, error) { var msg C.zmq_msg_t if i, err := C.zmq_msg_init(&msg); i != 0 { return []byte{}, errget(err) } defer C.zmq_msg_close(&msg) var size C.int var err error var i C.int i, err = C.zmq_recv(soc.soc, &msg, C.int(flags)) if i == 0 { size = C.int(C.zmq_msg_size(&msg)) } else { size = -1 } if size < 0 { return []byte{}, errget(err) } if size == 0 { return []byte{}, nil } data := make([]byte, int(size)) C.memcpy(unsafe.Pointer(&data[0]), C.zmq_msg_data(&msg), C.size_t(size)) return data, nil }
// Receive a message from the socket. // int zmq_recv (void *s, zmq_msg_t *msg, int flags); func (s *zmqSocket) Recv(flags SendRecvOption) (data []byte, err error) { // Allocate and initialise a new zmq_msg_t err = nil var m C.zmq_msg_t if C.zmq_msg_init(&m) != 0 { println("init") err = errno() return } defer C.zmq_msg_close(&m) // Receive into message if C.zmq_recvmsg(s.s, &m, C.int(flags)) != 0 { println("recvmsg") err = errno() return } // Copy message data into a byte array // FIXME Ideally this wouldn't require a copy. size := C.zmq_msg_size(&m) if size > 0 { data = make([]byte, int(size)) C.memcpy(unsafe.Pointer(&data[0]), C.zmq_msg_data(&m), size) } else { data = nil } return }
func (m *AACDecoder) Decode(data []byte) (sample []byte, err error) { r := C.aacdec_decode( &m.m, (*C.uint8_t)(unsafe.Pointer(&data[0])), (C.int)(len(data)), ) if int(r) < 0 { err = errors.New("decode failed") return } if int(m.m.got) == 0 { err = errors.New("no data") return } size := int(m.m.f.linesize[0]) * 2 sample = make([]byte, size*2) for i := 0; i < 2; i++ { C.memcpy( unsafe.Pointer(&sample[i*size]), unsafe.Pointer(m.m.f.data[i]), (C.size_t)(size), ) } return }
// NewTensor converts from a Go value to a Tensor. Valid values are scalars, // slices, and arrays. Every element of a slice must have the same length so // that the resulting Tensor has a valid shape. func NewTensor(value interface{}) (*Tensor, error) { val := reflect.ValueOf(value) dims, dataType, err := dimsAndDataTypeOf(val.Type()) if err != nil { return nil, err } // TODO(ashankar): Remove the bytes.Buffer and endcode directly into // C-memory, avoiding the memcpy and cutting down memory usage in half. shape := make([]int64, dims) buf := new(bytes.Buffer) if err := encodeTensor(buf, shape, val); err != nil { return nil, err } var shapePtr *C.int64_t if len(shape) > 0 { shapePtr = (*C.int64_t)(unsafe.Pointer(&shape[0])) } t := &Tensor{ c: C.TF_AllocateTensor(C.TF_DataType(dataType), shapePtr, C.int(len(shape)), C.size_t(buf.Len())), shape: shape, } runtime.SetFinalizer(t, (*Tensor).finalize) if buf.Len() > 0 { slice := buf.Bytes() // https://github.com/golang/go/issues/14210 C.memcpy(C.TF_TensorData(t.c), unsafe.Pointer(&slice[0]), C.size_t(buf.Len())) } return t, nil }
func (d *Disassembler) Bytes() []byte { b := make([]byte, d.Len()) C.memcpy(unsafe.Pointer(&b[0]), unsafe.Pointer(C.ud_insn_ptr(&d.u)), C.size_t(d.Len())) return b }
//export GoFileWrite // Returns SQLite error code to be returned by xWrite: // SQLITE_OK: wrote n bytes // SQLITE_IOERR_WRITE: got error while writing // SQLITE_FULL: partial write func GoFileWrite(fd C.int, src *C.char, n C.int, offset C.long) (rv int) { println("writing", n, "bytes at offset", offset, "to fd", fd) defer func() { println("write returning", rv) }() file := GetFile(int(fd)) if file == nil { return C.SQLITE_IOERR_WRITE } // TODO: avoid this copy buf := make([]byte, n) C.memcpy(unsafe.Pointer(&buf[0]), unsafe.Pointer(src), C.size_t(len(buf))) nwritten, err := file.WriteAt(buf, int64(offset)) if err != nil { if err == os.ENOSPC { return C.SQLITE_FULL } return C.SQLITE_IOERR_WRITE } if nwritten != int(n) { return C.SQLITE_IOERR_WRITE } return C.SQLITE_OK }
//export GoFileRead // Returns SQLite error code to be returned by xRead: // SQLITE_OK: read n bytes // SQLITE_IOERR_READ: got error while reading // SQLITE_IOERR_SHORT_READ: read fewer than n bytes; rest will be zeroed func GoFileRead(fd C.int, dst *C.char, n C.int, offset C.long) (rv int) { println("reading", n, "bytes at offset", offset, "from fd", fd) defer func() { println("read returning", rv) }() file := GetFile(int(fd)) if file == nil { return C.SQLITE_IOERR_READ } buf := make([]byte, n) curbuf := buf for n > 0 { read, err := file.ReadAt(curbuf, int64(offset)) curbuf = curbuf[read:] n -= C.int(read) if err == os.EOF { break } if err != nil { return C.SQLITE_IOERR_READ } } C.memcpy(unsafe.Pointer(dst), unsafe.Pointer(&buf[0]), C.size_t(len(buf))) if n != 0 { return C.SQLITE_IOERR_SHORT_READ } return C.SQLITE_OK }
func (p *Pcap) Next() (*Packet, os.Error) { var header *C.struct_pcap_pkthdr var buf *C.u_char switch C.pcap_next_ex(p.cptr, &header, &buf) { case 0: return nil, os.NewError("read time out") case -1: return nil, os.NewError(p.Geterror()) case -2: return nil, os.NewError("savefile eof") } ret := new(Packet) ret.Time.Sec = int32(header.ts.tv_sec) ret.Time.Usec = int32(header.ts.tv_usec) ret.Caplen = uint32(header.caplen) ret.Len = uint32(header.len) ret.Data = make([]byte, header.caplen) if header.caplen > 0 { C.memcpy(unsafe.Pointer(&ret.Data[0]), unsafe.Pointer(buf), C.size_t(header.caplen)) } return ret, nil }
// Compile pattern with jit compilation. flagC is Compile flags, // flagS is study flag. func CompileJIT(pattern string, flagsC, flagsS int) (Regexp, error) { patternC := C.CString(pattern) defer C.free(unsafe.Pointer(patternC)) if clen := int(C.strlen(patternC)); clen != len(pattern) { return Regexp{}, fmt.Errorf("%s (%d): %s", pattern, clen, "NUL byte in pattern", ) } var errptr *C.char var erroffset C.int ptr := C.pcre_compile(patternC, C.int(flagsC), &errptr, &erroffset, nil) if ptr == nil { return Regexp{}, fmt.Errorf("%s (%d): %s", pattern, int(erroffset), C.GoString(errptr), ) } psize := pcresize(ptr) var re Regexp re.ptr = make([]byte, psize) C.memcpy(unsafe.Pointer(&re.ptr[0]), unsafe.Pointer(ptr), psize) errS := re.study(flagsS) if errS != nil { return re, fmt.Errorf("study error: %s", errS) } return re, nil }
func (self *Surface) ClipRectangleList() ([]Rectangle, Status) { list := C.cairo_copy_clip_rectangle_list(self.context) defer C.cairo_rectangle_list_destroy(list) rects := make([]Rectangle, int(list.num_rectangles)) C.memcpy(unsafe.Pointer(&rects[0]), unsafe.Pointer(list.rectangles), C.size_t(list.num_rectangles*8)) return rects, Status(list.status) }
//export aqbankingGetPasswordFn func aqbankingGetPasswordFn(token *C.char, buffer unsafe.Pointer, minLen, maxLen int) int { pin, ok := knownAqbankingPins[C.GoString(token)] if ok { C.memcpy(buffer, unsafe.Pointer(C.CString(pin)), C.size_t(len(pin))) } return 0 }
//export callback_friend_message func callback_friend_message( c_tox *C.Tox, c_friend_number C.uint32_t, c_message_type C.TOX_MESSAGE_TYPE, c_message *C.uint8_t, c_length C.size_t, c_user_data unsafe.Pointer, ) { // Initialize variables. tox := (*Tox)(c_user_data) friendNumber := uint32(c_friend_number) var messageType ToxMessageType switch c_message_type { case C.TOX_MESSAGE_TYPE_NORMAL: messageType = ToxMessageTypeNormal case C.TOX_MESSAGE_TYPE_ACTION: messageType = ToxMessageTypeAction } message := make([]byte, c_length) // Copy the chat message. if c_length > 0 { C.memcpy( unsafe.Pointer(&message[0]), unsafe.Pointer(c_message), c_length, ) } // Register the callback. tox.onFriendMessage(tox, friendNumber, messageType, message) }
/* int xs_recv (void *sck,void *buf,size_t len,int flags) */ func (sck *xsSocket) Recv(flags SocketOption) ([]byte, error, uint64) { var msg C.xs_msg_t r := C.xs_msg_init(&msg) if r != 0 { return nil, errno(), 0 } defer C.xs_msg_close(&msg) r = C.xs_recvmsg(sck.sck, &msg, C.int(flags)) if r == -1 { return nil, errno(), 0 } size := C.xs_msg_size(&msg) var more uint64 more_size := C.size_t(unsafe.Sizeof(more)) C.xs_getmsgopt(&msg, C.XS_MORE, unsafe.Pointer(&more), &more_size) if size > 0 { data := make([]byte, int(size)) C.memcpy(unsafe.Pointer(&data[0]), C.xs_msg_data(&msg), size) return data, nil, more } return nil, nil, more /* nothing to recv */ }
// Move pattern to the Go heap so that we do not have to use a // finalizer. PCRE patterns are fully relocatable. (We do not use // custom character tables.) func toheap(ptr *C.pcre) (re Regexp) { defer C.free(unsafe.Pointer(ptr)) size := pcresize(ptr) re.ptr = make([]byte, size) C.memcpy(unsafe.Pointer(&re.ptr[0]), unsafe.Pointer(ptr), size) return }
func (ctx *TPMContext) Random(n uint32) (rdata []byte, err error) { var randbytes *C.BYTE result := C.Tspi_TPM_GetRandom(ctx.tpm, C.UINT32(n), &randbytes) if result != C.TSS_SUCCESS { switch result { case C.TSS_E_INVALID_HANDLE: return nil, ErrInvalidHandle case C.TSS_E_INTERNAL_ERROR: return nil, ErrInternalError case C.TSS_E_BAD_PARAMETER: return nil, ErrBadParameter default: return nil, ErrUnknown } } rand := C.malloc(C.size_t(n)) if rand != nil { C.memcpy(rand, unsafe.Pointer(randbytes), C.size_t(n)) rdata = C.GoBytes(rand, C.int(n)) C.free(rand) } C.Tspi_Context_FreeMemory(ctx.ctx, randbytes) return }
// Import imports the nodes and edges from a serialized representation of // another Graph into g. // // Names of imported nodes will be prefixed with prefix. func (g *Graph) Import(def []byte, prefix string) error { cprefix := C.CString(prefix) defer C.free(unsafe.Pointer(cprefix)) opts := C.TF_NewImportGraphDefOptions() defer C.TF_DeleteImportGraphDefOptions(opts) C.TF_ImportGraphDefOptionsSetPrefix(opts, cprefix) buf := C.TF_NewBuffer() defer C.TF_DeleteBuffer(buf) // Would have preferred to use C.CBytes, but that does not play well // with "go vet" till https://github.com/golang/go/issues/17201 is // resolved. buf.length = C.size_t(len(def)) buf.data = C.malloc(buf.length) if buf.data == nil { return fmt.Errorf("unable to allocate memory") } defer C.free(buf.data) C.memcpy(buf.data, unsafe.Pointer(&def[0]), buf.length) status := newStatus() C.TF_GraphImportGraphDef(g.c, buf, opts, status.c) if err := status.Err(); err != nil { return err } return nil }
//export go_ReadResponse func go_ReadResponse( self *C.struct__cef_resource_handler_t, data_out unsafe.Pointer, bytes_to_read C.int, bytes_read *C.int, callback *C.struct__cef_callback_t) int { if handler, ok := handlerMap[unsafe.Pointer(self)]; ok { dataOut, bytesRead, result := handler.resourceHandler.ReadResponse( int(bytes_to_read), CefCallbackT{callback}, ) if len(dataOut) != bytesRead { panic(fmt.Sprintf("The response given to ReadResponse is invalid. bytes given %d is does not equal bytesRead %d", len(dataOut), bytesRead)) } dataOutCString := C.CString(string(dataOut)) defer C.free(unsafe.Pointer(dataOutCString)) C.memcpy(data_out, unsafe.Pointer(dataOutCString), C.size_t(bytesRead)) *bytes_read = C.int(bytesRead) return result } return 0 }
// Receive a message from the socket. // int zmq_recv (void *s, zmq_msg_t *msg, int flags); func (s *Socket) Recv(flags SendRecvOption) (data []byte, err error) { // Allocate and initialise a new zmq_msg_t var m C.zmq_msg_t var rc C.int if rc, err = C.zmq_msg_init(&m); rc != 0 { err = casterr(err) return } defer C.zmq_msg_close(&m) // Receive into message if rc, err = C.zmq_recvmsg(s.s, &m, C.int(flags)); rc == -1 { err = casterr(err) return } err = nil // Copy message data into a byte array // FIXME Ideally this wouldn't require a copy. size := C.zmq_msg_size(&m) if size > 0 { data = make([]byte, int(size)) C.memcpy(unsafe.Pointer(&data[0]), C.zmq_msg_data(&m), size) } else { data = nil } return }
func (this *CodecCtx) CopyExtra(ist *Stream) *CodecCtx { codec := this.avCodecCtx icodec := ist.CodecCtx().avCodecCtx codec.bits_per_raw_sample = icodec.bits_per_raw_sample codec.chroma_sample_location = icodec.chroma_sample_location codec.codec_id = icodec.codec_id codec.codec_type = icodec.codec_type // codec.codec_tag = icodec.codec_tag codec.rc_max_rate = icodec.rc_max_rate codec.rc_buffer_size = icodec.rc_buffer_size codec.field_order = icodec.field_order codec.extradata = (*_Ctype_uint8_t)(C.av_mallocz((_Ctype_size_t)((C.uint64_t)(icodec.extradata_size) + C.FF_INPUT_BUFFER_PADDING_SIZE))) C.memcpy(unsafe.Pointer(codec.extradata), unsafe.Pointer(icodec.extradata), (_Ctype_size_t)(icodec.extradata_size)) codec.extradata_size = icodec.extradata_size codec.bits_per_coded_sample = icodec.bits_per_coded_sample codec.has_b_frames = icodec.has_b_frames return this }
// Return input with pattern replaced by sub. func reSub(pattern []byte, sub []byte, input []byte) []byte { var err *C.GError = nil re := C.g_regex_new( (*C.gchar)(data(append(pattern, 0))), C.G_REGEX_CASELESS| C.G_REGEX_RAW| C.G_REGEX_NO_AUTO_CAPTURE| C.G_REGEX_OPTIMIZE, 0, &err) if err != nil { panic("g_regex_new") } defer C.g_regex_unref(re) subd := C.g_regex_replace_literal(re, (*C.gchar)(data(input)), C.gssize(len(input)), 0, (*C.gchar)(data(sub)), 0, &err) if err != nil { panic("g_regex_replace_literal") } defer C.g_free(C.gpointer(subd)) l := C.strlen((*C.char)(subd)) rv := make([]byte, l) C.memcpy(data(rv), unsafe.Pointer(subd), l) return rv }
//export doLoad func doLoad( self unsafe.Pointer, offset C.size_t, source unsafe.Pointer, length C.size_t) C.int { model := (*machine.Model)(self) // Bump up the size to the end of the page. new_length := platform.Align(uint64(length), platform.PageSize, true) // Allocate the backing data. data, err := model.Map( machine.MemoryTypeUser, platform.Paddr(offset), new_length, true) if err != nil { // Things are broken. log.Print("Error during ElfLoad: ", err) return -C.int(syscall.EINVAL) } // Copy the data in. C.memcpy(unsafe.Pointer(&data[0]), source, length) // All good. return 0 }
func (msg *Msg) onDecode(pbData *C.BYTE, cbData C.DWORD, fFinal bool) error { if int(cbData) > msg.maxN { return fmt.Errorf("Buffer overrun on decoding") } C.memcpy(msg.data, unsafe.Pointer(pbData), C.size_t(cbData)) msg.n = int(cbData) return nil }
//export goKvCursorCallback func goKvCursorCallback(data unsafe.Pointer, b uint, fn unsafe.Pointer) int { if b == 0 { return 0 } pdata := make([]byte, b) C.memcpy(unsafe.Pointer(&pdata[0]), data, C.size_t(b)) f := *(*func([]byte) int)(fn) return f(pdata) }
// cairo_path_t* cairo_copy_path_flat (cairo_t *cr); func (self *Surface) CopyPathFlat() (PathData, Status) { path := C.cairo_copy_path_flat(self.context) defer C.cairo_path_destroy(path) raw_data := make(PathData, int(path.num_data*2)) C.memcpy(unsafe.Pointer(&raw_data[0]), unsafe.Pointer(path.data), C.size_t(path.num_data*16)) return raw_data, Status(path.status) }
func (f *Face) CopyIndices() []uint32 { indices := make([]uint32, f.mNumIndices) if unsafe.Sizeof(C.uint(0)) != unsafe.Sizeof(uint32(0)) { panic("wrong size") } size := uint32(unsafe.Sizeof(C.uint(0))) * f.NumIndices() C.memcpy(unsafe.Pointer(&indices[0]), unsafe.Pointer(f.mIndices), C.size_t(size)) return indices }
func DBFReadStringAttribute(h DBFHandle, shapeIndex, fieldIndex int) []byte { cstr := C.DBFReadStringAttribute(h, C.int(shapeIndex), C.int(fieldIndex)) slen := int(C.strlen(cstr)) bytes := make([]byte, slen) if slen > 0 { C.memcpy(unsafe.Pointer(&bytes[0]), unsafe.Pointer(cstr), C.size_t(slen)) } return bytes }