Skip to content

Instantly share code, notes, and snippets.

@tosone
Forked from zchee/cgo.md
Last active July 21, 2019 13:11
Show Gist options
  • Save tosone/2e4120e7d28fd1c42adfb2ab12ab5bb5 to your computer and use it in GitHub Desktop.
Save tosone/2e4120e7d28fd1c42adfb2ab12ab5bb5 to your computer and use it in GitHub Desktop.
[Golang CGO] #Go

See also, http://libraryofalexandria.io/cgo/

Using Go cgo

cgo has a lot of trap.
but Not "C" pkg also directory in $GOROOT/src. IDE's(vim) Goto command not works.

So, Here collect materials.

cgo compiling file extension

C

.c, .s, .S

C++

.cc, .cpp, .cxx

Header

Any .h, .hh, .hpp, .hxx files will not be compiled separately.
but, if these header files are changed, the C and C++ files will be recompiled.

cgo environment variable

Building Go

CC, CXX, CC_FOR_TARGET, CXX_FOR_TARGET

Compiling .go

CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS, CGO_LDFLAGS

cgo convert C-Go string type

string

// Go string to C string; result must be freed with C.free
func C.CString(string) *C.char

// C string to Go string
func C.GoString(*C.char) string

// C string, length to Go string
func C.GoStringN(*C.char, C.int) string

// C pointer, length to Go []byte
func C.GoBytes(unsafe.Pointer, C.int) []byte

C Types in Go

char

type C.char
type C.schar (signed char)
type C.uchar (unsigned char)

short

type C.short
type C.ushort (unsigned short)

int

type C.int
type C.uint (unsigned int)

long

type C.long
type C.ulong (unsigned long)

longlong

type C.longlong (long long)
type C.ulonglong (unsigned long long)

float

type C.float  

double

type C.double

Directly access struct type

As in C.struct_stat

struct

type C.struct_***

union

type C.union_***

enum

type C.enum_***

void*

See also https://golang.org/pkg/unsafe/

func unsafe.Pointer() *ArbitraryType
char --> C.char --> byte
signed char --> C.schar --> int8
unsigned char --> C.uchar --> uint8
short int --> C.short --> int16
short unsigned int --> C.ushort --> uint16
int --> C.int --> int
unsigned int --> C.uint --> uint32
long int --> C.long --> int32 or int64
long unsigned int --> C.ulong --> uint32 or uint64
long long int --> C.longlong --> int64
long long unsigned int --> C.ulonglong --> uint64
float --> C.float --> float32
double --> C.double --> float64
wchar_t --> C.wchar_t -->
void * -> unsafe.Pointer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment