Vasudev Kamath: Working around type system of Go with unsafe
Go language has a strong type system unlike C, and some times this
will be head ache when we want to interact with C data types with Cgo
or just to convert a Go type to lets say byte slice. I recently faced
the same problem and after poking around things, I learned the Go
provides unsafe package which can be used to work around the Go's
type system.
Problem
Recently I started using Cgo to use some C library I had to write
some tools for development and testing. The reason I chose Go for
this was prototyping and writing some quick tools is much easier in Go
than done in C.
The C library had some function which takes pointer to array types and
fills it with some values. The problem I was facing here was how to
create a C array in Go. Go does have array but its largely used as
internal representation for much efficient type called slice and I
can't directly cast a byte slice into an C array.
Second problem I had was I had to store arbitrary Go types like float
(float32,float64) and int (int32, int64) etc. into C array.
So in brief, the problems that needed to solve are
- Find a way to convert byte slice from Go into C array and vice versa.
- Find a way to convert and store Go types into a C array.
Solution
Basically C array are sequence of memory location which can be
statically or dynamically allocated. In Cgo its possible to access C
standard library functions for memory allocation, so why not use
it. The memory allocation function then returns the pointer to
starting of allocated memory, we can use this pointer to write Go's
bytes into the memory location and bytes from memory location into
Go's slice.
The pointer returned by C allocation functions are not directly usable
for memory dereferencing in Go, here is where unsafe package kicks
in. We will cast the return of C allocation function as
unsafe.Pointer type and from the documentation of unsafe package,
Functions are written just for this post and they don't really do
anything. As you can see ArrayReadFunc takes a pointer to array and
fills it with content of another array using memcpy. Function
ArrayWriteFunc on other hand takes pointer to array and copies its
content to internal array. I've added print logic to ArrayWriteFunc
just to show that values passed from Go are making it here.
Below is the Go code which uses the above C files passes byte slice to
get value out of C code and array made of byte slice to C function to
send values in.
Functions ReadArray and WriteArray are just wrapper to the calls
to C counter parts ArrayReadFunc and ArrayWriteFunc. ReadArray
returns unsafe.Pointer which is allocated C array and should be
freed by caller. WriteArray takes unsafe.Pointer which is pointing
to memory location containing C array.
Now the functions of interest are CArrayToByteSlice and
ByteSliceToCArray. It should be pretty clear from the above code to
understand what is happening in these functions. Still I will just put
explain them briefly.
ByteSliceToCArray allocates a C array using calloc from C standard
library. It then creates a uintptr, a pointer type in Go which is
used to dereference the each memory location and store bytes from the
input byte slice in them.
CArrayToByteSlice on other hands creates a uintptr type by casting
input unsafe.Pointer type and then uses this pointer type to
dereference values from memoy and store it in byte slice with suitable
casting.
So lets build the code and run it and see the output:
This function is generic which can take various types of value. First
we will use Go's type assertion to determine the type and creates a
uintptr pointer for the value and allocates byte slice depending on
the size of the value as calculated using unsafe.Sizeof. Later it
uses the pointer to dereference value from memory location and copies
each byte into byte slice. The idea used here is every type is
represented as certain number of bytes in the memory. Below is the
entire program.
The above conversion can also be achieved using encoding/binary
package provided by Go. But its been told to me that it
makes things pretty slow.
So we can then cast unsafe.Pointer to uintptr which is the Go type which is large enough to hold any memory address in Go and can be used for pointer arithmetic just like we do in C (of course with some more castings). Below I'm pasting a simplified code in C which I wrote for this post.
- A pointer value of any type can be converted to a Pointer.
- A Pointer can be converted to a pointer value of any type.
- A uintptr can be converted to a Pointer.
- A Pointer can be converted to a uintptr.
#ifndef __BYTETEST_H__
#define __BYTETEST_H__
typedef unsigned char UBYTE;
extern void ArrayReadFunc(UBYTE *arrayout);
extern void ArrayWriteFunc(UBYTE *arrayin);
#endif
#include "bytetest.h"
#include <stdio.h>
#include <string.h>
void ArrayReadFunc(UBYTE *arrayout)
UBYTE array[20] = 1, 2, 3, 4,5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17,
18, 19, 20 ;
memcpy(arrayout, array, 20);
void ArrayWriteFunc(UBYTE *arrayin)
UBYTE array[20];
memcpy(array, arrayin, 20);
printf("Byte slice array received from Go:\n");
for(int i = 0; i < 20; i ++)
printf("%d ", array[i]);
printf("\n");
package main
/*
#cgo CFLAGS: -std=c99
#include "bytetest.h"
#include <stdlib.h>
*/
import "C"
import (
"fmt"
"unsafe"
)
func ReadArray() unsafe.Pointer
var outArray = unsafe.Pointer (C.calloc(20,1))
C.ArrayReadFunc((*C.UBYTE)(outArray))
return outArray
func WriteArray(inArray unsafe.Pointer)
C.ArrayWriteFunc((*C.UBYTE)(inArray))
func CArrayToByteSlice(array unsafe.Pointer, size int) []byte
var arrayptr = uintptr(array)
var byteSlice = make([]byte, size)
for i := 0; i < len(byteSlice); i ++
byteSlice[i] = byte(*(*C.UBYTE)(unsafe.Pointer(arrayptr)))
arrayptr ++
return byteSlice
func ByteSliceToCArray (byteSlice []byte) unsafe.Pointer
var array = unsafe.Pointer(C.calloc(C.size_t(len(byteSlice)), 1))
var arrayptr = uintptr(array)
for i := 0; i < len(byteSlice); i ++
*(*C.UBYTE)(unsafe.Pointer(arrayptr)) = C.UBYTE(byteSlice[i])
arrayptr ++
return array
func main()
carray := ReadArray()
defer C.free(carray)
carraybytes := CArrayToByteSlice(carray, 20)
fmt.Println("C array converted to byte slice:")
for i := 0; i < len(carraybytes); i ++
fmt.Printf("%d ", carraybytes[i])
fmt.Println()
gobytes := []byte 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40
gobytesarray := ByteSliceToCArray(gobytes)
defer C.free(gobytesarray)
WriteArray(gobytesarray)
C array converted to byte slice: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Byte slice array received from Go: 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40So yes it actually works and values are moving across C and Go. This solves first problem in hand next is converting arbitrary Go types into byte slices. There are many cases where we would like to convert an arbitrary Go types like (int, float) into bytes. One such use case I found was when writing a TCP client for communicating with a Server written using C speaking custom protocol. Here I'm just going to show how to convert types like float, int to byte slice, I've not tried converting structures but it is certainly possible. Below is the function which can convert int32,float32 into byte slice it can also be extended for other types.
func CopyValueToByte(value interface ) []byte
var valptr uintptr
var slice []byte
switch t := value.(type)
case int32:
i := value.(int32)
valptr = uintptr(unsafe.Pointer(&i))
slice = make([]byte, unsafe.Sizeof(i))
case float32:
f := value.(float32)
valptr = uintptr(unsafe.Pointer(&f))
slice = make([]byte, unsafe.Sizeof(f))
default:
fmt.Fprintf(os.Stderr,"Unsupported type: %T\n", t)
os.Exit(1)
for i := 0; i < len(slice); i++
slice[i] = byte(*(*byte)(unsafe.Pointer(valptr)))
valptr++
return slice
package main
import (
"fmt"
"unsafe"
"os"
)
func CopyValueToByte(value interface ) []byte
var valptr uintptr
var slice []byte
switch t := value.(type)
case int32:
i := value.(int32)
valptr = uintptr(unsafe.Pointer(&i))
slice = make([]byte, unsafe.Sizeof(i))
case float32:
f := value.(float32)
valptr = uintptr(unsafe.Pointer(&f))
slice = make([]byte, unsafe.Sizeof(f))
default:
fmt.Fprintf(os.Stderr,"Unsupported type: %T\n", t)
os.Exit(1)
for i := 0; i < len(slice); i++
slice[i] = byte(*(*byte)(unsafe.Pointer(valptr)))
valptr++
return slice
func main()
a := float32(-10.3)
floatbytes := CopyValueToByte(a)
fmt.Println("Float value as byte slice:")
for i := 0; i < len(floatbytes); i++
fmt.Printf("%x ", floatbytes[i])
fmt.Println()
b := new(float32)
bptr := uintptr(unsafe.Pointer(b))
for i := 0; i < len(floatbytes); i++
*(*byte)(unsafe.Pointer(bptr)) = floatbytes[i]
bptr++
fmt.Printf("Byte value copied to float var: %f\n", *b)
Conclusion
So goes unsafe.Pointer is really powerful thing which allows us to
work around the Go's type system but as package documentation says
it should be used with care
PS: I'm not really sure if its recommended to use allocation functions from C standard library, I will wait for expert gophers to comment on that.
Or, "Why 2014 will NOT be the year of Linux in the desktop".
So, it happens that my mum (66 yo) has been a Debian user for over a year now. With highs and lows, she manages to do what she needs; sometimes I need to intervene.
Today I thought I could send her a quick email explaining how to download using BitTorrent, because of reasons. So, as I was writing, I realised that in many torrent sites, you only get a magnet link these days. No problem! Click on the magnet link, at it should work automagically.
Then I remembered: it works on my computer, because I've spent a couple of hours some time ago researching how to make FireFox work with magnet links, creating a custom script, etc. I hoped that by now this must have been solved, at least in Debian unstable.
Wrong again. I created a new user in my computer, launched IceWeasel/FireFox and boom: I get a dialog asking me to select a program, not from a list of desktop applications, taken from one of the gazillion sources where applications are defined, but just from any place on the file system! (At least, now you don't need to go tweaking with the hidden FireFox configuration editor).
I was very angry at the brainiac at Mozilla who thought it was a great idea to ignore the host system and do their own MIMEtype handling. And then, tried Chromium to see what would happen... And I get first a scary message telling me that it is going to use the super-obscure
Brief Glamor Hacks
Eric Anholt started writing Glamor a few years ago. The goal was to
provide credible 2D acceleration based solely on the OpenGL API, in
particular, to implement the X drawing primitives, both core and
Render extension, without any GPU-specific code. When he started,
the thinking was that fixed-function devices were still relevant, so
that original code didn t insist upon modern OpenGL features like
GLSL shaders. That made the code less efficient and hard to write.
Glamor used to be a side-project within the X world; seen as something
that really wasn t very useful; something that any credible 2D driver
would replace with custom highly-optimized GPU-specific code. Eric and
I both hoped that Glamor would turn into something credible and that
we d be able to eliminate all of the horror-show GPU-specific code in
every driver for drawing X text, rectangles and composited
images. That hadn t happened though, until now.
Fast forward to the last six months. Eric has spent a bunch of time
cleaning up Glamor internals, and in fact he s had it merged into the
core X server for version 1.16 which will be coming up this July.
Within the Glamor code base, he s been cleaning some internal
structures up and making life more tolerable for Glamor developers.
Using libepoxy
A big part of the cleanup was a transition all of the extension
function calls to use his other new project,
Moving from Lilo to GRUB, using LVM as default, etc throughout the last years it was time to evaluate how well LVM works without a separate boot partition, possibly also on top of Software RAID. Big disks are asking for partitioning with GPT, just UEFI isn t my default yet, so I m still defaulting to Legacy BIOS for Debian/wheezy (I expect this to change for Debian/jessie and according hardware approaching at my customers).
So what we have and want in this demonstration setup:
I was super sad to know that 
I thought it might be a good idea for Zoe to do something out of the
ordinary while Sarah was away, to help pass the time, so I booked The Cow
House, one of the
In my article
Debian Women is proud to announce that it will hold a
To "pedestal" an aerobar means to elevate the bars above the basebar using risers instead of using headset spacers:
So, assuming you currently have a bike that uses headset spacers, what would be the effect on your position if you were to replace, say, a 10mm headset spacer with a 10mm armrest riser?
First, let us consider the effect of removing the headset spacer. The crucial insight is that removing a 10mm spacer will not lower the
My last update about ongoing development of botch, the bootstrap/build ordering
tool chain, was three months ago with the
For small Qt-projects, I have for a long time been using qmake, mostly because qmake -project gives me a working build in most cases, but once the project grows a bit, I have switched to cmake because there is just things there I like better.
So, I thought how to start with cmake instead, and ended up writing a small script. I guess I should share it:
A new major release 0.11.0 of