Search code examples
crustffi

Can a Rust constant/static be exposed to C?


Say I have a Rust API that contains a constant or a static, an i32 for example. I want to use this Rust API from C. From the C side, I want to use that constant as an array size. Am I correct that there is no way to do it? Is the best solution to redeclare the constant in my C header files that are providing the declarations for the rest of the Rust API?

Update: To be more specific, I am using a compiler which does not support variable-length arrays (Visual C++ 2005)


Solution

  • You most certainly can do it, at least inside functions:

    cnst.rs:

    #[no_mangle]
    pub static X: i32 = 42;
    

    cnstuse.c:

    #include <stdint.h>
    #include <stdio.h>
    
    extern const int32_t X;
    
    int main() {
        char data[X];
        printf("%lu\n", sizeof(data));
        return 0;
    }
    

    Compilation:

    % rustc --crate-type=staticlib cnst.rs
    note: link against the following native artifacts when linking against this static library
    note: the order and any duplication can be significant on some platforms, and so may need to be preserved
    note: library: System
    note: library: pthread
    note: library: c
    note: library: m
    % gcc -o cnstuse cnstuse.c libcnst.a
    % ./cnstuse
    42
    

    Top-level array declarations, however, can't use global variables/constants for size, so this will only work inside functions.