func (repo *Repository) ListBranches(flags ...BranchType) ([]string, error) { var cnames C.git_strarray defer C.git_strarray_free(&cnames) var cflags C.uint if len(flags) == 0 { cflags = C.uint(BRANCH_ALL) } else { for _, flag := range flags { cflags |= C.uint(flag) } } ecode := C.git_branch_list(&cnames, repo.git_repository, cflags) if ecode != git_SUCCESS { return nil, gitError() } // TODO: Find a safer way if one exists. var namesSlice reflect.SliceHeader length := int(cnames.count) namesSlice.Data = uintptr(unsafe.Pointer(cnames.strings)) namesSlice.Len = length namesSlice.Cap = length cnameStrings := *(*[]*C.char)(unsafe.Pointer(&namesSlice)) names := make([]string, length) for i := 0; i < len(cnameStrings); i++ { names[i] = C.GoString(cnameStrings[i]) } return names, nil }
/** * Parses an IPTC data blob generating a map of records and tags to * string values. */ func parseIptcData(iptcData *C.IptcData) (Data, error) { parsed := Data{} for i := C.uint(0); i < iptcData.count; i++ { dataSet := C.get_iptc_dataset(iptcData, i) if parsed[int(dataSet.record)] == nil { parsed[int(dataSet.record)] = make(map[int]string) } switch C.iptc_dataset_get_format(dataSet) { case C.IPTC_FORMAT_BYTE, C.IPTC_FORMAT_SHORT, C.IPTC_FORMAT_LONG: parsed[int(dataSet.record)][int(dataSet.tag)] = fmt.Sprintf("%d", C.iptc_dataset_get_value(dataSet)) case C.IPTC_FORMAT_BINARY: value := make([]C.char, 256) C.iptc_dataset_get_as_str(dataSet, &value[0], C.uint(len(value))) parsed[int(dataSet.record)][int(dataSet.tag)] = fmt.Sprintf("%c", value[:(dataSet.size*3)-1]) default: value := make([]C.uchar, 256) actualLength := C.iptc_dataset_get_data(dataSet, &value[0], C.uint(len(value))) parsed[int(dataSet.record)][int(dataSet.tag)] = fmt.Sprintf("%s", value[:actualLength-1]) } } return parsed, nil }
// New initializes a new Map. func New() *Map { return &Map{ m: C.mapnik_map(C.uint(800), C.uint(600)), width: 800, height: 600, } }
func (db *Db) Get(_txn *Txn, key []byte, getbuff *uintptr, flags uint32) ([]byte, error) { var data *C.char = (*C.char)(unsafe.Pointer(*getbuff)) var datalen C.uint var txn *C.DB_TXN = nil if _txn != nil { txn = _txn.txn } ret := C.db_get( db.db, txn, (*C.char)(unsafe.Pointer(&key[0])), C.uint(len(key)), &data, &datalen, C.uint(flags), ) err := ResultToError(ret) if err == nil { *getbuff = uintptr(unsafe.Pointer(data)) if data == nil { return nil, nil } else { r := C.GoBytes(unsafe.Pointer(data), C.int(datalen)) //C.free(unsafe.Pointer(data)) return r, nil } } return nil, err }
func (v *VirStorageVol) WipePattern(algorithm uint32, flags uint32) error { result := C.virStorageVolWipePattern(v.ptr, C.uint(algorithm), C.uint(flags)) if result == -1 { return GetLastError() } return nil }
func (this *Geos) Polygon(exterior *Geom, interiors []*Geom) *Geom { if len(interiors) == 0 { geom := C.GEOSGeom_createPolygon_r(this.v, exterior.v, nil, C.uint(0)) if geom == nil { return nil } err := C.GEOSNormalize_r(this.v, geom) if err != 0 { C.GEOSGeom_destroy(geom) return nil } return &Geom{geom} } interiorPtr := make([]*C.GEOSGeometry, len(interiors)) for i, geom := range interiors { interiorPtr[i] = geom.v } geom := C.GEOSGeom_createPolygon_r(this.v, exterior.v, &interiorPtr[0], C.uint(len(interiors))) if geom == nil { return nil } err := C.GEOSNormalize_r(this.v, geom) if err != 0 { C.GEOSGeom_destroy(geom) return nil } return &Geom{geom} }
func ImageFilterSubUint(src1, dest []byte, c uint) bool { _src1 := (*C.uchar)(unsafe.Pointer(&src1[0])) _dest := (*C.uchar)(unsafe.Pointer(&dest[0])) _len := C.uint(min(len(src1), len(dest))) _c := C.uint(c) return C.SDL_imageFilterSubUint(_src1, _dest, _len, _c) == 0 }
func (s *Shout) updateParameters() { // set hostname p := C.CString(s.Host) C.shout_set_host(s.struc, p) C.free(unsafe.Pointer(p)) // set port C.shout_set_port(s.struc, C.ushort(s.Port)) // set username p = C.CString(s.User) C.shout_set_user(s.struc, p) C.free(unsafe.Pointer(p)) // set password p = C.CString(s.Password) C.shout_set_password(s.struc, p) C.free(unsafe.Pointer(p)) // set mount point p = C.CString(s.Mount) C.shout_set_mount(s.struc, p) C.free(unsafe.Pointer(p)) // set format C.shout_set_format(s.struc, C.uint(s.Format)) // set protocol C.shout_set_protocol(s.struc, C.uint(s.Protocol)) }
// DescribeWorkdir describes the working tree. It means describe HEAD // and appends <mark> (-dirty by default) if the working tree is dirty. func (repo *Repository) DescribeWorkdir(opts *DescribeOptions) (*DescribeResult, error) { var resultPtr *C.git_describe_result var cDescribeOpts *C.git_describe_options if opts != nil { var cpattern *C.char if len(opts.Pattern) > 0 { cpattern = C.CString(opts.Pattern) defer C.free(unsafe.Pointer(cpattern)) } cDescribeOpts = &C.git_describe_options{ version: C.GIT_DESCRIBE_OPTIONS_VERSION, max_candidates_tags: C.uint(opts.MaxCandidatesTags), describe_strategy: C.uint(opts.Strategy), pattern: cpattern, only_follow_first_parent: cbool(opts.OnlyFollowFirstParent), show_commit_oid_as_fallback: cbool(opts.ShowCommitOidAsFallback), } } runtime.LockOSThread() defer runtime.UnlockOSThread() ecode := C.git_describe_workdir(&resultPtr, repo.ptr, cDescribeOpts) if ecode < 0 { return nil, MakeGitError(ecode) } return newDescribeResultFromC(resultPtr), nil }
func Prepare(fun *Function, nargs uint) (*Callable, int) { var cif C.ffi_cif var typp *C.ffi_type ffi_type_void := ffi_type_for(TYPE_VOID, nil) // recover from panic here defer func() { if x := recover(); x != nil { println("panicking with value", x) } println("function returns normally") // executes only when hideErrors==true }() call := &Callable{} println("cif size: ", unsafe.Sizeof(cif)) call.cifmem = Allocate(unsafe.Sizeof(cif) + 100) call.argimem = Allocate(unsafe.Sizeof(typp) * 10) call.cif = &call.cifs // (*C.ffi_cif)(call.cifmem.Ptr()) // fmt.Println("cif ABI, nargs:", int(call.cif.abi), int(call.cif.nargs)) call.cif.abi = C.FFI_DEFAULT_ABI call.cif.nargs = C.uint(nargs) call.fun = fun call.cif.rtype = &ffi_type_void //stat := 777 println("cif address:", (unsafe.Pointer)(call.cif)) println("void type address:", (unsafe.Pointer)(&ffi_type_void)) println("cgo void type address:", (unsafe.Pointer)(&C.ffi_type_void)) stat := C.ffi_prep_cif(call.cif, C.FFI_DEFAULT_ABI, C.uint(nargs), &ffi_type_void, nil) /*&C.ffi_type_void, (**C.ffi_type)(call.argimem.ptr))*/ return call, int(stat) }
func nWrapString(uc *C.SAP_UC, length C.int, strip bool) (result string, err error) { var rc C.RFC_RC var errorInfo C.RFC_ERROR_INFO if length == -1 { length = C.int(C.GoStrlenU((*C.SAP_UTF16)(uc))) } if length == 0 { return "", err } utf8Size := C.uint(length*3) + 1 utf8str := (*C.char)(unsafe.Pointer(C.malloc((C.size_t)(utf8Size)))) defer C.free(unsafe.Pointer(utf8str)) // _todo: Memory access error on Windows only, when trying to free RFCCHAR1 of RFCTABLE in function call test *utf8str = 0 resultLen := C.uint(0) rc = C.RfcSAPUCToUTF8(uc, (C.uint)(length), (*C.RFC_BYTE)(utf8str), &utf8Size, &resultLen, &errorInfo) if rc != C.RFC_OK { return result, rfcError(errorInfo, "Failed wrapping a C string") } result = C.GoStringN(utf8str, length) if strip { result = strings.Trim(result, "\x00 ") return } return }
//Set both the verdict for the packet and a data buffer containing the packet //data func (p *NFPacket) SetResult(v Verdict, data []byte) { if data == nil { p.resultChannel <- C.struct_NFResult{Verdict: C.uint(v), Data: nil, Len: 0} } else { p.resultChannel <- C.struct_NFResult{Verdict: C.uint(v), Data: (*C.uint8_t)(&data[0]), Len: (C.int)(len(data))} } }
//export go_callback func go_callback(queueId C.int, data *C.uchar, length C.int, cb *chan NFPacket) VerdictModified { xdata := C.GoBytes(unsafe.Pointer(data), length) packet := gopacket.NewPacket(xdata, layers.LayerTypeIPv4, gopacket.DecodeOptions{ Lazy: true, NoCopy: true, SkipDecodeRecovery: false, }) p := NFPacket{ verdictChannel: make(chan Verdict), verdictModifiedChannel: make(chan VerdictPacket), Packet: packet, } select { case (*cb) <- p: select { case v := <-p.verdictModifiedChannel: return VerdictModified{ verdict: C.uint(v.Verdict), data: (*C.uchar)(unsafe.Pointer(&v.Packet[0])), length: C.uint(len(v.Packet)), } case v := <-p.verdictChannel: return VerdictModified{ verdict: C.uint(v), data: nil, length: 0, } } default: return VerdictModified{verdict: C.uint(NF_DROP), data: nil, length: 0} } }
func Ellipse(x, y, a, b int, n, f bool) { // x0, y0 := C.int(x-a), C.int(y-b) if f { if !n { C.XSetFunction(display, graphicsContext, C.GXinvert) } // C.GXcopyInverted ? if !xxb { C.XFillArc(display, C.Drawable(window), graphicsContext, C.int(x0), C.int(y0), C.uint(2*a), C.uint(2*b), 0, 64*360) } C.XFillArc(display, C.Drawable(pixmap), graphicsContext, C.int(x0), C.int(y0), C.uint(2*a), C.uint(2*b), 0, 64*360) } else { if !n { C.XSetFunction(display, graphicsContext, C.GXinvert) } if !xxb { C.XDrawArc(display, C.Drawable(window), graphicsContext, C.int(x0), C.int(y0), C.uint(2*a), C.uint(2*b), 0, 64*360) } C.XDrawArc(display, C.Drawable(pixmap), graphicsContext, C.int(x0), C.int(y0), C.uint(2*a), C.uint(2*b), 0, 64*360) } if !n { C.XSetFunction(display, graphicsContext, C.GXcopy) } C.XFlush(display) }
//export go_callback func go_callback(queueId C.int, dev C.uint32_t, hookid C.uint8_t, data *C.uchar, length C.int, cb *chan NFPacket) VerdictModified { xdata := C.GoBytes(unsafe.Pointer(data), length) p := NFPacket{ verdictChannel: make(chan Verdict), verdictModifiedChannel: make(chan VerdictPacket), InPacket: xdata, HookId: Hook(hookid), DevIx: int(dev), } select { case (*cb) <- p: select { case v := <-p.verdictModifiedChannel: return VerdictModified{ verdict: C.uint(v.Verdict), data: (*C.uchar)(unsafe.Pointer(&v.Packet[0])), length: C.uint(len(v.Packet)), } case v := <-p.verdictChannel: return VerdictModified{ verdict: C.uint(v), data: nil, length: 0, } } default: return VerdictModified{verdict: C.uint(NF_DROP), data: nil, length: 0} } }
func hsCompile(expression string, flags CompileFlag, mode ModeFlag, info *hsPlatformInfo) (hsDatabase, error) { var db *C.hs_database_t var err *C.hs_compile_error_t var platform *C.hs_platform_info_t if info != nil { platform = &info.platform } expr := C.CString(expression) ret := C.hs_compile(expr, C.uint(flags), C.uint(mode), platform, &db, &err) C.free(unsafe.Pointer(expr)) if ret == C.HS_SUCCESS { return db, nil } if err != nil { defer C.hs_free_compile_error(err) } if ret == C.HS_COMPILER_ERROR && err != nil { return nil, &compileError{C.GoString(err.message), int(err.expression)} } return nil, fmt.Errorf("compile error, %d", int(ret)) }
// Return true if the file header contains instrument information for the file. false otherwise. func (f *File) SetInstrument(i *Instrument) bool { c := new(C.SF_INSTRUMENT) c.gain = C.int(i.Gain) c.basenote = C.char(i.Basenote) c.detune = C.char(i.Detune) c.velocity_lo = C.char(i.Velocity[0]) c.velocity_hi = C.char(i.Velocity[1]) c.key_lo = C.char(i.Key[0]) c.key_hi = C.char(i.Key[1]) c.loop_count = C.int(i.LoopCount) var index int for ; index < i.LoopCount; index++ { c.loops[index].mode = C.int(i.Loops[index].Mode) c.loops[index].start = C.uint(i.Loops[index].Start) c.loops[index].end = C.uint(i.Loops[index].End) c.loops[index].count = C.uint(i.Loops[index].Count) } for ; index < 16; index++ { c.loops[index].mode = C.int(None) // why is this necessary? libsndfile doesn't check loopcount for AIFF } r := C.sf_command(f.s, C.SFC_SET_INSTRUMENT, unsafe.Pointer(c), C.int(unsafe.Sizeof(*c))) return (r == C.SF_TRUE) }
// NewSized initializes a new Map with the given size. func NewSized(width, height int) *Map { return &Map{ m: C.mapnik_map(C.uint(width), C.uint(height)), width: width, height: height, } }
func (vchannel *VirtioChannel) remap() error { if vchannel.QueueAddress.Value != 0 { // Can we map this address? vchannel_size := C.vring_size( C.uint(vchannel.QueueSize.Value), platform.PageSize) mmap, err := vchannel.VirtioDevice.mmap( platform.Paddr(4096*vchannel.QueueAddress.Value), uint64(vchannel_size)) if err != nil { return err } // Initialize the ring. C.vring_init( &vchannel.vring, C.uint(vchannel.QueueSize.Value), unsafe.Pointer(&mmap[0]), platform.PageSize) // Notify the consumer. vchannel.notifications <- VirtioNotification{} } else { // Leave the address cleared. No notifcations // will be processed as per the Write() function. vchannel.Consumed = 0 } return nil }
func NewVirConnectionWithAuth(uri string, username string, password string) (VirConnection, error) { var cUri *C.char authMechs := C.authMechs() defer C.free(unsafe.Pointer(authMechs)) cUsername := C.CString(username) defer C.free(unsafe.Pointer(cUsername)) cPassword := C.CString(password) defer C.free(unsafe.Pointer(cPassword)) cbData := C.authData(cUsername, C.uint(len(username)), cPassword, C.uint(len(password))) defer C.free(unsafe.Pointer(cbData)) auth := C.virConnectAuth{ credtype: authMechs, ncredtype: C.uint(2), cb: C.virConnectAuthCallbackPtr(unsafe.Pointer(C.authCb)), cbdata: unsafe.Pointer(cbData), } if uri != "" { cUri = C.CString(uri) defer C.free(unsafe.Pointer(cUri)) } ptr := C.virConnectOpenAuth(cUri, (*C.struct__virConnectAuth)(unsafe.Pointer(&auth)), C.uint(0)) if ptr == nil { return VirConnection{}, GetLastError() } obj := VirConnection{ptr: ptr} return obj, nil }
func (d *VirDomain) SetVcpusFlags(vcpu uint16, flags uint) error { result := C.virDomainSetVcpusFlags(d.ptr, C.uint(vcpu), C.uint(flags)) if result == -1 { return GetLastError() } return nil }
/** * \brief Parse the given source file and the translation unit corresponding * to that file. * * This routine is the main entry point for the Clang C API, providing the * ability to parse a source file into a translation unit that can then be * queried by other functions in the API. This routine accepts a set of * command-line arguments so that the compilation can be configured in the same * way that the compiler is configured on the command line. * * \param CIdx The index object with which the translation unit will be * associated. * * \param source_filename The name of the source file to load, or NULL if the * source file is included in \p command_line_args. * * \param command_line_args The command-line arguments that would be * passed to the \c clang executable if it were being invoked out-of-process. * These command-line options will be parsed and will affect how the translation * unit is parsed. Note that the following options are ignored: '-c', * '-emit-ast', '-fsyntex-only' (which is the default), and '-o <output file>'. * * \param num_command_line_args The number of command-line arguments in * \p command_line_args. * * \param unsaved_files the files that have not yet been saved to disk * but may be required for parsing, including the contents of * those files. The contents and name of these files (as specified by * CXUnsavedFile) are copied when necessary, so the client only needs to * guarantee their validity until the call to this function returns. * * \param num_unsaved_files the number of unsaved file entries in \p * unsaved_files. * * \param options A bitmask of options that affects how the translation unit * is managed but not its compilation. This should be a bitwise OR of the * CXTranslationUnit_XXX flags. * * \returns A new translation unit describing the parsed code and containing * any diagnostics produced by the compiler. If there is a failure from which * the compiler cannot recover, returns NULL. */ func (idx Index) Parse(fname string, args []string, us UnsavedFiles, options TranslationUnitFlags) TranslationUnit { var ( c_fname *C.char = nil c_us = us.to_c() ) defer c_us.Dispose() if fname != "" { c_fname = C.CString(fname) } defer C.free(unsafe.Pointer(c_fname)) c_nargs := C.int(len(args)) c_cmds := make([]*C.char, len(args)) for i, _ := range args { cstr := C.CString(args[i]) defer C.free(unsafe.Pointer(cstr)) c_cmds[i] = cstr } var c_args **C.char = nil if len(args) > 0 { c_args = &c_cmds[0] } o := C.clang_parseTranslationUnit( idx.c, c_fname, c_args, c_nargs, c_us.ptr(), C.uint(len(c_us)), C.uint(options)) return TranslationUnit{o} }
// setUpRing sets up the shared-memory ring buffer between the user process and the kernel. func (h *TPacket) setUpRing() (err error) { totalSize := C.uint(h.opts.framesPerBlock * h.opts.numBlocks * h.opts.frameSize) switch h.tpVersion { case TPacketVersion1, TPacketVersion2: var tp C.struct_tpacket_req tp.tp_block_size = C.uint(h.opts.blockSize) tp.tp_block_nr = C.uint(h.opts.numBlocks) tp.tp_frame_size = C.uint(h.opts.frameSize) tp.tp_frame_nr = C.uint(h.opts.framesPerBlock * h.opts.numBlocks) if _, err := C.setsockopt(h.fd, C.SOL_PACKET, C.PACKET_RX_RING, unsafe.Pointer(&tp), C.socklen_t(unsafe.Sizeof(tp))); err != nil { return fmt.Errorf("setsockopt packet_rx_ring: %v", err) } case TPacketVersion3: var tp C.struct_tpacket_req3 tp.tp_block_size = C.uint(h.opts.blockSize) tp.tp_block_nr = C.uint(h.opts.numBlocks) tp.tp_frame_size = C.uint(h.opts.frameSize) tp.tp_frame_nr = C.uint(h.opts.framesPerBlock * h.opts.numBlocks) tp.tp_retire_blk_tov = C.uint(h.opts.blockTimeout / time.Millisecond) if _, err := C.setsockopt(h.fd, C.SOL_PACKET, C.PACKET_RX_RING, unsafe.Pointer(&tp), C.socklen_t(unsafe.Sizeof(tp))); err != nil { return fmt.Errorf("setsockopt packet_rx_ring v3: %v", err) } default: return errors.New("invalid tpVersion") } if h.ring, err = C.mmap(nil, C.size_t(totalSize), C.PROT_READ|C.PROT_WRITE, C.MAP_SHARED, C.int(h.fd), 0); err != nil { return } if h.ring == nil { return errors.New("no ring") } return nil }
func (w *writer) Write(b []byte) (n int, err error) { if len(b) == 0 { return 0, nil } w.bzStream.next_in = (*C.char)(unsafe.Pointer(&b[0])) w.bzStream.avail_in = C.uint(len(b)) for w.bzStream.avail_in > 0 { // Compress the available data. w.bzStream.next_out = (*C.char)(unsafe.Pointer(&w.outBuffer[0])) w.bzStream.avail_out = C.uint(len(w.outBuffer)) ret := C.BZ2_bzCompress(&w.bzStream, C.BZ_RUN) if ret != C.BZ_RUN_OK { return len(b) - int(w.bzStream.avail_in), translateError(ret) } // Write the contents of the output buffer to the underlying writer. if err = w.writeAvailOut(); err != nil { return len(b) - int(w.bzStream.avail_in), err } } return len(b), nil }
func max(a, b C.int) C.uint { if a > b { return C.uint(a) } return C.uint(b) }
func cstringArray(strings []string) **C.char { c := C.mkStringArray(C.uint(len(strings))) for i, str := range strings { C.addStringToArray(c, C.CString(str), C.uint(i)) } return c }
func (strm *zstream) setOutBuf(buf []byte, size int) { if buf == nil { C.zlibstream_set_out_buf(&strm[0], nil, C.uint(size)) } else { C.zlibstream_set_out_buf(&strm[0], unsafe.Pointer(&buf[0]), C.uint(size)) } }
func (m *Material) GetMaterialProperty(key MatKey, typ TextureType, textureIndex int) (*MaterialProperty, Return) { pKey := key.constString() var pPropOut *C.struct_aiMaterialProperty ret := C.aiGetMaterialProperty((*C.struct_aiMaterial)(m), pKey, C.uint(typ), C.uint(textureIndex), &pPropOut) return (*MaterialProperty)(pPropOut), Return(ret) }
func (this *Geos) CreateCoordSeq(size, dim uint32) (*CoordSeq, error) { result := C.GEOSCoordSeq_create_r(this.v, C.uint(size), C.uint(dim)) if result == nil { return nil, CreateError("could not create CoordSeq") } return &CoordSeq{result}, nil }
func main() { c := C.struct_columns{15, 30, 45} sum := C.sum_columns(c) fmt.Println(sum) var a int = 15 var b int = 30 s := C.sum_vals((C.int)(a), (C.int)(b)) //调用C语言的函数 fmt.Println(s) var goSum int = int(sum) //C语言的int转成Golang的int类型 fmt.Println(goSum) in := []byte("test") inLen := len(in) out := (*C.uchar)(C.malloc(16)) outLen := C.uint(16) r := C.update((*C.uchar)(&in[0]), C.uint(inLen), out, &outLen) if r == 0 { fmt.Printf("outlen=%d\n", outLen) dst := fmt.Sprintf("%02X", C.GoBytes(unsafe.Pointer(out), C.int(outLen))) fmt.Println(dst) } //C.free(unsafe.Pointer(out)) }