Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for offsetof constants #1659

Closed
dcoles opened this issue Oct 27, 2019 · 2 comments
Closed

Support for offsetof constants #1659

dcoles opened this issue Oct 27, 2019 · 2 comments

Comments

@dcoles
Copy link

dcoles commented Oct 27, 2019

A number of C libraries make use of offsetof as a primitive form of reflection. Often this will be exposed as a get_object_foo helpers or used to define _OFFSET constants which are used as part of the API. It would be useful if bindgen could evaluate these expressions and expand them into usize constants.

As you probably are aware, Rust does not currently provide a built-in offset_of macro which makes it difficult to reproduce this functionality on the Rust side.

Input C/C++ Header

#define offsetof(type, member) __builtin_offsetof(type, member)

#define FOO_X_OFFSET offsetof(struct Foo, x)

struct Foo {
        int x;
};

Bindgen Invocation

$ bindgen offset.h --blacklist-type Foo

Actual Results

No constant is generated:

/* automatically generated by rust-bindgen */

Expected Results

A usize typed constant with the offset of the member x in struct Foo:

/* automatically generated by rust-bindgen */

pub const FOO_X_OFFSET: usize = 0;
@emilio
Copy link
Contributor

emilio commented Oct 28, 2019

Hi, thanks for filing :)

This works already if you do:

const unsigned FOO_X_OFFSET = offsetof(struct Foo, x);

as far as I can tell. Evaluating offsetof in macros is generally impossible, as macros are context-dependent. Of course you can do somewhat of a best-effort guess, but I wouldn't be in favor of that, plus it'd generally be pretty hacky.

More general macro improvements should be probably directed to the rust-cexpr, though I think realistically this is out of scope for that crate. Stuff like #316 and such should totally be feasible though.

@emilio emilio closed this as completed Oct 28, 2019
@dcoles
Copy link
Author

dcoles commented Oct 28, 2019

Oh! Wonderful. Thank you. :)
Didn't even think to try a constant. I can certainly work with that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants