Home > Software engineering >  How to pass any Go variable into a C function that accepts a void *?
How to pass any Go variable into a C function that accepts a void *?

Time:09-17

I have the following function set in C:

void set(void *data)
{
    // do some work with data (which points to a Go variable)
}

Now, in Go I need to have a function that accepts any variable as a parameter and calls the C function set passing this parameter to it. How can I do this? Can we do it by having the Go function accepting a parameter like data interface{}, call unsafe.Pointer passing this parameter, and then call the C function with the result of unsafe.Pointer?

CodePudding user response:

As long as you are following the constraints detailed in the passing pointers section of the CGO documentation, you can create a Go wrapper function accepting an empty interface argument, and extract the pointer value using reflect.

func Set(i interface{}) {
    C.set(unsafe.Pointer(reflect.ValueOf(i).Pointer()))
}
  • Related