cbindgen icon indicating copy to clipboard operation
cbindgen copied to clipboard

Support 'pub const BAR: &CStr = c"hello world";'

Open rlidwka opened this issue 1 year ago • 8 comments

We have C string literals now stabilized in Rust since https://github.com/rust-lang/rust/issues/105723 (since v1.77.0, which'll be released next month).

It seems reasonable to have const string literals like these:

use std::ffi::CStr;
pub const BAR: &CStr = c"hello world";

and convert them to #define or constexpr or whatever cbindgen usually does with constants

Current behavior is very much not ideal (probably need to update syn to v2?):

$ cbindgen --lang C
thread 'main' panicked at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/syn-1.0.109/src/lit.rs:1020:13:
Unrecognized literal: `c"hello world"`

rlidwka avatar Feb 10 '24 17:02 rlidwka

actually, that's not supported yet in syn: https://github.com/dtolnay/syn/issues/1502

rlidwka avatar Feb 10 '24 17:02 rlidwka

Seems like sending a PR to syn would be the way to go, then once that's merged we can use it...

emilio avatar Apr 14 '24 22:04 emilio

Seems like sending a PR to syn would be the way to go, then once that's merged we can use it...

looks like it's already merged: https://github.com/dtolnay/syn/pull/1622

rlidwka avatar Apr 15 '24 07:04 rlidwka

@emilio I am currently blocked from using C string literals in my project due to this issue. Would be great to pull in the latest syn and publish a new version of cbindgen.

benma avatar May 14 '24 06:05 benma

We presumably also need to use them somehow right? Maybe can be a follow-up tho.

emilio avatar May 14 '24 10:05 emilio

I believe this can be closed since PR #961 was merged

GrayJack avatar Jun 23 '24 20:06 GrayJack

Ah, I just found the Unrecognized literal panic. It would be cool if a new release was cut so I could use c literals.

RossSmyth avatar Jul 01 '24 20:07 RossSmyth

Also do note that this does not fix the issue of #324 namely that &CStr is not FFI compatible. Rust's CStr is a fat pointer, so you cannot expect that a pub const CStr to be able to be passed to C(++).

It is currently documented that it may become a thin pointer in the future, but it seems less likely as time goes on.

RossSmyth avatar Jul 12 '24 17:07 RossSmyth