Create C bindings #689
Johannesd3
started this conversation in
Feature Requests
Replies: 1 comment 10 replies
-
I believe C bindings were discussed at some point a few years ago, but work never really progressed on them. My thoughts on it are limited since I have no need of them/plan to use them, though can understand why they might be useful. I think any development should happen in a completely seperate repository though, purely for separation of concerns. |
Beta Was this translation helpful? Give feedback.
10 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
@d4rwel inspired me to write down some thoughts I had about creating C bindings for librespot. There's no need to change anything in librespot itself, it could happen in its own crate/repo. I assume that #665 is ready, but it could also be accomplished with git dependencies.
So here's a rough plan:
Create a rust library crate and add the following to the
Cargo.toml
:Pick some important Rust functions from librespot. Maybe look at the examples to decide what's needed.
Create functions that are callable from C as shown in
this gist, or rather this repository.Important: Wrap everything into a catch_unwind. If an error occurs, there might be UB if it reaches the border to C.
There are certainly some structs that need to be passed. Since those structs are not compatible with C, they must be passed as opaque type behind a pointer (as in the example).
Some functions are
async
. These functions must be executed by a tokio runtime. Create functions to created and destroy a tokio runtime. Return this runtime as opaque struct. (This struct could even be calledlibrespot
if the user shouldn't be bothered with implementation details.) For every function call that executes an async rust function, a pointer to this struct must be passed.Remember, destructors in Rust are implicit. It's important to create functions that deallocate resources again, although these functions seem to do nothing. Look at the example above.
If it's ready, running
cargo build
will produce a.so
file intarget/debug
.Run
cargo install cbindgen
to install a tool to create a C header file.cbindgen --lang c
will hopefully spit out the expected result.You can now write a C application that uses librespot. Just include the header and link it against this
.so
file.How does it sound?
Beta Was this translation helpful? Give feedback.
All reactions