作者:runco
项目:goss
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
}
作者:Gim
项目:go-mrub
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
}
作者:dvarrazz
项目:pge
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
}
作者:tonymagr
项目:us
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
}
作者:jjacquay71
项目:GoRod
// 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
}
}
}
作者:quantum142
项目:tavl
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)))
}
}
}
作者:vine
项目:go-db-drive
// 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
}
作者:thought-machin
项目:pleas
//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
}
作者:phacop
项目:canva
// 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
}
作者:varnamprojec
项目:libvarnam-golan
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
}
作者:ryderku
项目:v8.g
//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)
}
作者:kuba-
项目:c-go-zi
//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
}
作者:wi
项目:git2g
//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")
}
}
作者:mier8
项目:gokogir
//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)
}
}
作者:rputika
项目:sbm
//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
}
作者:Gwil
项目:go-
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
}
作者:sn-ambe
项目:gda
// 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
}
作者:vanadiu
项目:go.swif
//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))
}
}()
}
作者:extram
项目:g
// 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
}
作者:hooklif
项目:govi
// 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
}