in reply to What's the "modern" way to talk to C libraries?

Personally, I like to start out with Inline::C, and then pull out the XS file that Inline generates. This gives me a quick start without needing to worry too much, but Inline::C still has me writing C and the interface doesn't really create perlish APIs. I usually wrap the C part then with more Perl to create a perlish API over the C API.

The ugly part IMO is handling structs that you get from C. I haven't found a good way to automatically generate a converter from a C-struct to a Perl hash (and be it a tied hash into the C data structure). Convert::Binary::C did this, but if it is failure-prone nowadays, that's no fun. I have enough to debug with the segfaults in my code, I don't want segfaults introduced by other code as well...

Replies are listed 'Best First'.
Re^2: What's the "modern" way to talk to C libraries?
by haj (Vicar) on Nov 24, 2025 at 11:16 UTC

    This was my initial step, too: Run the PipeWire tutorial sources in Inline::C. But then, I did not want write my own stuff in C.

    And yes, handling structs is the interesting part. PipeWire comes with ~200 header files and way too many structs to do that manually. Convert::Binary::C (CBC) does exactly this: Convert a C struct into a Perl hash (reference) at runtime. It also provides all the meta data I need: If a struct contains a struct some *thing, then the conversion will give me a Perl scalar containing the pointer as an integer value, and CBC also tells me that this scalar is a pointer to struct some, which then can be recursively unraveled. That's pretty awesome.

    CBC is not error prone at runtime: It does not cause segfaults. It says that it can not handle the syntax in some header files which happens during the development cycle. Working around this is a bit annoying, but not impossible.

    The main downside with my current project is the lack of portability. PipeWire is Linux-only, no chance on Windows. Its headers can only be compiled with GCC, not a big restriction when we are on Linux anyway. It also does not work with system Perl (or any other Perl built with useithreads=define). So while I can shrug it away, that code is unlikely to be useful on CPAN and will never make it into a Linux distribution.

      Usually i like to use Inline::C and/or handcode stuff, but...

      The last two weeks i had to make Bindings to some closed source library (only headers + .so available) for work. My enthusiasm for supporting binary blobs is limited at best. So i asked AI (claude) to do all the low level XS stuff for me, starting with h2xs to make the project, then generate all the missing stuff and generate a high level Perl module on top of that.

      It's not perfect, but it works (for the most part).

      It's called Lib::Pepper

      PerlMonks XP is useless? Not anymore: XPD - Do more with your PerlMonks XP
      Also check out my sisters artwork and my weekly webcomics