c-for-go
c-for-go copied to clipboard
How to pass a Go function pointer/callback to a C function?
Hello,
Thanks for creating this great tool. I'm creating a binding for Soundpipe. I was just wondering, the library has a function called:
int sp_process_plot(sp_data *sp, void *ud, void (*callback)(sp_data *, void *)) { ... }
Which gives me this Go signature after running c-for-go:
func Process(sp *Data, ud unsafe.Pointer, callback *func(arg0 *Data, arg1 unsafe.Pointer)) int32 { ... }
So, I have created a Go callback function like this:
func writeOsc(sp *soundpipe.Data, data unsafe.Pointer) { ... }
Then I want to pass writeOsc
as callback to Process
:
soundpipe.Process(sp, &ud, writeOsc)
But the types do not match for the callback:
- my writeOsc is a
type func (sp *soundpipe.Data, data unsafe.Pointer)
- the callback is a
type *func (sp *soundpipe.Data, data unsafe.Pointer)
(notice the additional *)
I tried to do soundpipe.Process(sp, &ud, &writeOsc
, but Go says I can't take the address of writeOsc
. Any clue on how I should pass a Go function callback to this function?
Thanks.
@delthas Any luck with this issue? I am trying to solve a similar one.
@delthas @faisal00813 hey, isn't this an example of what is needed? https://github.com/xlab/vorbis-go/blob/master/cmd/vorbis-player/main.go#L134
@xlab Thank you for pointing to that code. It helped. But my issue was to generate functions in GO from the inline callback functions. e.g https://github.com/hyperledger/indy-sdk/blob/4b2cc8ddf83a06dc375fee89bdd2a878beab706e/vcx/libvcx/include/vcx.h#L140 I think this is not supported as of now.
Workaround was to define the callbacks and then use them in function. e.g https://github.com/faisal00813/vcx-go/blob/f70b84cdeb83f17c52f0c72a04ddff65fc49937a/vcx/vcx.h#L42
@faisal00813 yep, you should have a type, btw, I advice to avoid modifying the original headers, and instead add another .h to the YAML spec with custom code and bridges. Good luck