#Go struct memory layout compared to C

37 messages · Page 1 of 1 (latest)

unborn furnace
#

this is comically unsafe

#

yes, you can definitely do it

#

and it should work, most of the time

#

but it would be safer to use a real c struct, with cgo

#

usually the best approach, when you need to expose this functionality to users, is hiding the C struct unexported behind a go struct, and exposing get/set methods

#

if you don't want to do get/set methods you can also have the go struct mirror the fields of the C struct, and then when it comes to calling the C method, construct the C struct locally there, or have the C struct be a field of the go struct, and only synchronize values between them when used

#

:)

#

i prefer raw cgo, but to each their own

#

at runtime..

#

like,, you don't know what kind of structs you'll get?

#

well, it is and it isn't

#

it's doable now, but it's completely unsupported and could break with any update

#

how are you constructing go structs at runtime?

#

this is definitely an interesting use case

#

the safest way to do this is read up on how C constructs structs in memory

#

and then "fake" it

#

(i am talking out of my ass with this example, i don't know how C actually does it) but let's take this as an example

typedef struct Foo {
  int x;
}

let's say C serializes this as literally just an int

#

so you could just turn an int into a byte array, and pass the pointer to that to C

#

this gets more and more complex the more stuff is in a struct of course

#

and don't even get me started on touples

#

lol

#

this would be my first impulse anyways, i can not guarantee that this is the best way to do it

#

yeah i've had mixed results converting c struct pointers to go structs

#

maybe if you exclusively use C datatypes it's a bit safer

#

im gonna POC this again and see how robust it is

#

maybe you won't need libffi

#

it's really doubtful that go would randomly decide to mess with memory layout of structs

#

especially since it's been pretty much unchanged for a while now

#

yeah you'll likely run into some edge cases but

#

for the most part the memory layout seems fine

#

seems to be okay shrug

#

it's still comically unsafe but,,, almost everything i do is comically unsafe

#

i mod unity games with go Hehe

#

so as long as you can use C types with reflection it should be fine, if not, that makes things a bit harder

#

well, they're not predefined in the reflect package, but you can define them yourself

something like

var CStringType = reflect.TypeOf(C.CString("hi"))
unborn furnace
#

lol yep that's my approach to just about everything Hehe