Is it possible to "mock" C definitions?

Hello,

Let me explain what I currently have:

  • A third party dynamic library and its C header file
  • A -sys crate generating Rust raw bindings using bindgen, it also links to the dynamic library during its build.rs
  • A wrapper crate that uses the -sys crate

I would like another crate (say -mock) to implement the C symbols that the -sys crate exports. Is that possible?
I know two ways to do this:

  • I can blacklist the function during bindgen and pick the -mock function in the wrapper, all of this behind a feature flag (kinda eh but it works)
  • I can point cargo's search path to target/debug granted the -mock library has been built (not happy with that one)

I’m wondering if there’s no dead simple way to do this that I’m missing, it seems like a fairly simple usecase?

I couldn’t find anything when searching for my issue but I’m not exactly well versed in linking and the likes.

I’ve made a “short, self-contained example” repo that should help you get started if you have an idea on how to solve it: https://github.com/ldesgoui/sys_mock_example

Thanks!

Woops, I got it working, I believe: https://github.com/ldesgoui/sys_mock_example/commit/9ec28c3c6fd220b6608a03b66e6f282cf72bf306

I had tried #[link(..)] in -sys previously but it would fail the first time I’d try building. I assumed it had to be an attribute of the right extern "C" {} block rather than any old one.

Should I use a build.rs instead to do this in a real project?

Thanks

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.