'How do I pass a Go callback (function ptr) from Go to Rust via CGo?
I have:
- A Rust library that is compiled to a static C library
- A Go program that calls the Rust library's API via CGo
I wish to pass a Go function (as callback) to the Rust code, so it will be able to send logs back to my Go program during runtime, when its library API is executed. Something like sending the cb address and save it inside my already compiled Rust code.
I've examined some examples where Go passes a cb to C using CGo, and C invokes it and it does work. But I couldn't wrap my head around how to transmit that to the Rust code, as if I was 'stopped' at the C interface-side of things.
The only thing I could think about is to declare a mutable empty Global variable inside Rust's library and assign the Go cb to it by passing the cb as a parameter from Go side.
Would that make sense? Any other suggestions?
Solution 1:[1]
Don't pass this go callback to another programming language. If I got you right, you should provide a cgo function like
invokeGoCallback( funcID, arg1, arg2)
And you can pass your callback to C as funcID, which your go code knows. Then when C want invoke this function, invoke invokeGoCallback
with that funcID.
Then let us discuss, why ?
and C invokes it and it does work.
Dive into how cgo works, you would know that invoking go function in C stack need environment. See this link and _cgo_runtime_cgocall
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Frank Wang |