1

To sum, as helpfully stated by user 9072997:

Since unsafe.Pointer can convert between types that have the same underlying type, can unsafe.Pointer also convert between function types who's arguments & return values have the same underlying type?

I am wondering. unsafe.Pointer can as it says in the name, convert from type to type in unsafe way.

I am trying to learn unsafe.Pointer, and do not plan to use it in any production apps while I am doing so. But, I still have a question about a conversion.

If I am correct, a type like so: type MyIntegerType int32 can be cast with unsafe.Pointer back to an int.

var integer MyIntegerType = 1
var goInt = *(*int32)(unsafe.Pointer(&integer))

However, this leaves me confused a little bit. Is something like this possible also?

type JSExtFunc func(this Value, args Args) interface{}

func (f JSExtFunc) MarshalJS() js.Func {
    // I am not sure if this is correct.
    var function = *(*func(this js.Value, args []js.Value) interface{})(unsafe.Pointer(&f))
    return js.FuncOf(function)
}

// Arguments for wrapped functions.
type Args []js.Value
type Value js.Value

If it is, or isn't, can you explain why?

I have tested it in go playground with a simple example, and it does seem to work. It still does not answer my question if this is actually OK, or if this was a chance-thing.

Go-playground link

nigel239
  • 1,485
  • 1
  • 3
  • 23
  • 1
    Since `unsafe.Pointer` can convert between types that have the same underlying type, can `unsafe.Pointer` also convert between function types who's arguments & return values have the same underlying type? - Do I have the question right? – 9072997 Jul 24 '23 at 19:13
  • @9072997 Yes you do. – nigel239 Jul 24 '23 at 19:15
  • 1
    Using `unsafe` is always "unsafe", but with primitive types you at least have more assurances that the conversion is correct. It's not specified whether this should work consistently or not, but the mailing list may be a better resource for developers who could explain how likely it is to break. – JimB Jul 25 '23 at 13:29

0 Answers0