nickik
nickik

Reputation: 5881

Rust calling C, static const in C code

I have used rust-bindgen to generate rust interface code.

Now in the C code you can find this:

extern const struct mps_key_s _mps_key_ARGS_END;
#define MPS_KEY_ARGS_END (&_mps_key_ARGS_END)

Note that in the hole rest of the code _mps_key_ARGS_END does not appear again.

The macro MPS_KEY_ARGS_END gets used regularly amung other simular mps_key_s.

Now the code produced by rust-bindgen is this:

pub static _mps_key_ARGS_END: Struct_mps_key_s;

Now in C code here is a example usage:

extern void _mps_args_set_key(mps_arg_s args[MPS_ARGS_MAX], unsigned i,
                              mps_key_t key);

_mps_args_set_key(args, 0, MPS_KEY_ARGS_END);

In rust it looks like this:

pub fn _mps_args_set_key(args: [mps_arg_s, ..32u], i: ::libc::c_uint,
                         key: mps_key_t);

Now I try to call it like this:

_mps_args_set_key(args, 0 as u32, _mps_key_ARGS_END );

But I get a error:

error: mismatched types: expected *const Struct_mps_key_s, found Struct_mps_key_s (expected *-ptr, found enum Struct_mps_key_s)

I am not a good C programmer, and I dont even understand where these C static even get there values from.

Thanks for your help.

Edit:

Update based on the answer of Chris Morgan.

I added this code (note, I replaced *const mps_key_s with mps_key_t):

pub static MPS_KEY_ARGS_END: mps_key_t = &_mps_key_ARGS_END;

Just for some extra information on why Im using mps_key_t, in C:

typedef const struct mps_key_s *mps_key_t;

In rust:

pub type mps_key_t = *const Struct_mps_key_s;

This seams seam to work better then befor but now Im getting a bad crash:

error: internal compiler error: unexpected failure note: the compiler hit an unexpected failure path. this is a bug. note: we would appreciate a bug report: http://doc.rust-lang.org/complement-bugreport.html note: run with RUST_BACKTRACE=1 for a backtrace task 'rustc' failed at 'expected item, found foreign item _mps_key_ARGS_END::_mps_key_ARGS_END (id=1102)', /home/rustbuild/src/rust-buildbot/slave/nightly-linux/build/src/libsyntax/ast_map/mod.rs:327

Upvotes: 0

Views: 806

Answers (1)

Chris Morgan
Chris Morgan

Reputation: 90722

#define MPS_KEY_ARGS_END (&_mps_key_ARGS_END)

The & part indicates that it is taking a pointer to the object, that the type of MPS_KEY_ARGS_END will be mps_key_s const*. In Rust, that is *const mps_key_s (a raw pointer), and can be achieved in the same way as in C, &_mps_key_ARGS_END. You can define MPS_KEY_ARGS_END in a way that you can use conveniently like this:

static MPS_KEY_ARGS_END: *const mps_key_s = &_mps_key_ARGS_END;

Upvotes: 1

Related Questions