Can I define C functions that accept native Go types through CGo? -


for work i'm doing integrate existing library, ended needing write additional c code provide interface usable through cgo.

in order avoid redundant data copies, able pass standard go types (e.g. go strings) these c adapter functions.

i can see there gostring , gointerface types defined in header cgo generates use exported go functions, there way use these types in own function prototypes cgo recognise?

at moment, i've ended using void * in c prototypes , passing unsafe.pointer(&value) on go side. less clean i'd though (for 1 thing, gives c code ability write value).

update:

just clear, know difference between go's native string type , c char *. point since copying string data passed c function anyway, doesn't make sense have code on go side make own copy.

i understand string layout change in future version of go, , size may differ platform. cgo exposing type definitions match current platform me via documented _cgo_export.h header generates me, seems bit odd talk of being unspecified:

typedef struct { char *p; int n; } gostring; 

but there doesn't seem way use definition in prototypes visible cgo. i'm not overly worried binary compatibility, since code making use of definition part of go package, source level compatibility enough (and wouldn't big deal update package if wasn't case).

not really. cannot safely mix, example go strings (string) , c "strings" (*char) code without using provided helpers that, ie. gostring , cstring. reason conform language specs full copy of string's content between go , c worlds must made. not that, garbage collector must know consider (go strings) , ignore (c strings). , there more things this, let me keep simple here.

similar and/or other restrictions/problems apply other go "magical" types, map or interface{} types. in interface types case (but not it), it's important realize inner implementation of interface{} (again not type), is not specified , implementation specific.

that's not possible differences between, gc , gccgo. means code break @ time compiler developers decide change detail of (unspecified , non guaranteed) implementation.

additionally, though go doesn't (now) use compacting garbage collector, may change , without pinning mechanism, code accessing go run time stuff directly again doomed.

conclusion: pass simple entities arguments c functions. pod structs simple fields safe (pointer fields not). complex go types, use provided helpers go strings, exists (very good) reason.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -