Skip to content

FFI mechanism to declare a symbol for an array #54450

Description

@joshtriplett

If I have a C declaration

char *symbol = "hello world";

I can declare that symbol in Rust as

extern "C" { pub static symbol: *c_char; }

But if I have a C declaration

char symbol[] = "hello world";

I can't directly declare that in Rust in an immediately usable way. In this case, symbol refers directly to the array of characters; while in C it will "degrade" to a pointer if used in a context that expects a pointer, in Rust a declaration referring to symbol will refer to the characters directly. So, for instance, declaring it as a *c_char will result in a pointer whose numeric value contains the first sizeof::<*c_char>() bytes of "hello world".

Declaring symbol as a [c_char; 0] and then obtaining and using its pointer seems wrong.

I can think of a few useful ways to do this, one more straightforward than the other.

One would be to have a means of defining in an extern "C" block something that gets the value of the address of the symbol, just as if in C I'd written char *symbol_ptr = symbol; and then referenced that from Rust. That seems easy enough to do, modulo bikeshedding over the syntax to do so.

Another would be to define symbol as a C array of unknown length. However, that seems unfortunate to deal with.

The most ideal approach I can think of would be to define symbol as a [c_char; _] (using the elided size syntax from rust-lang/rfcs#2545), and then infer the size from the symbol size:

$ nm --print-size test.o 
0000000000000000 000000000000000c D symbol

I don't know how feasible that would be, but it'd be incredibly convenient.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-FFIArea: Foreign function interface (FFI)A-arrayArea: `[T; N]`C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions