Search code examples
crustheadershared-libraries

How to use a single-header library C file in Rust?


I have been researching this topic about 2 days. I found bindgen, cc, windows-dll, libc, dlopen or other rust crates. But I couldn't able to use a single-header library. I made the c library so I checked my library if my library has the problem but in python I can able to use. I saw this FFI RUST resource and I reviewed.

My OS: Windows 11

Rust/Cargo Version: 1.64

Visual Studio: 2022 Community

Single-Header C lib: Github

Main File: main.rs

#[link(name = "lib-name")] // This link name want '.a' or '.dll' extension I think
extern { fn vn_clear; } // Extern c function

fn main()
{
   unsafe { vn_clear(); } // 'unsafe' for FFI
   println!("Is this worked?");
}

I know this code would work every FFI library but I couldn't figured it out.

[package]
name = "rust-test"
version = "0.1.0"
edition = "2021"

[dependencies]
libc = "0.2.133"

Do you know a way to use a single-header C library in Rust?


Solution

  • You most certainly want to use bindgen to generate the function definitions in Rust from the C header file.

    There is an excellent step-by-step tutorial that creates such a binding for the bzip2 library. It should give you an idea of the steps required to achieve what you need.