Example #1
0
func main() {

	str := "Hello World"

	cstr := C.CString(str)
	defer free(cstr)

	dup := C.strdup(C.CString(str))
	defer free(dup)

	gostr := C.GoString(dup)

	fmt.Println(gostr)

}
func main() {
	// a go string
	go1 := "hello C"
	// allocate in C and convert from Go representation to C representation
	c1 := C.CString(go1)
	// go string can now be garbage collected
	go1 = ""
	// strdup, per task. this calls the function in the C library.
	c2 := C.strdup(c1)
	// free the source C string.  again, this is free() in the C library.
	C.free(unsafe.Pointer(c1))
	// create a new Go string from the C copy
	go2 := C.GoString(c2)
	// free the C copy
	C.free(unsafe.Pointer(c2))
	// demonstrate we have string contents intact
	fmt.Println(go2)
}
Example #3
0
// Encode writes the image to the given io.Writer, encoding
// it according to the info parameter. Please, see the
// Info type for the available encoding options.
func (im *Image) Encode(w io.Writer, info *Info) error {
	var ex C.ExceptionInfo
	C.GetExceptionInfo(&ex)
	defer C.DestroyExceptionInfo(&ex)
	if info == nil {
		info = NewInfo()
	}
	/* ImageToBlob copies the format from the image into
	the image info. Overwrite if required and then restore
	*/
	im.mu.Lock()
	var format *C.char
	copied := false
	if info.info.magick[0] != 0 {
		copied = true
		if im.image.magick[0] != 0 {
			format = C.strdup(&im.image.magick[0])
		}
		C.strncpy(&im.image.magick[0], &info.info.magick[0], C.MaxTextExtent)
	}
	var s C.size_t
	mem := imageToBlob(info, im, &s, &ex)
	if copied {
		/* Restore image format */
		if format != nil {
			C.strncpy(&im.image.magick[0], format, C.MaxTextExtent)
			C.free(unsafe.Pointer(format))
		} else {
			C.memset(unsafe.Pointer(&im.image.magick[0]), 0, C.MaxTextExtent)
		}
	}
	im.mu.Unlock()
	if mem == nil {
		return exError(&ex, "encoding")
	}
	b := goBytes(mem, int(s))
	w.Write(b)
	C.free(mem)
	return nil
}