-
Notifications
You must be signed in to change notification settings - Fork 694
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
Avoid assigning (wrong) types to constants using #define #2120
Comments
Yeah this is sorta expected. You can set the type via |
There exists an easy workaround when comparing (small) constants such as 1, 2, 3, or -1, -2 with a if some_ffi_module::some_func() == some_ffi_module::SOME_CONST as _ {
/* … */
} This cast should be okay if some_func's return type is big enough to contain the expected constant return value (which seems to be a reasonable assumption in most cases). But using When I would thus say that assigning particular types to constants using |
It is true they are just macros, but integer constants do have a type in C.
In C that works because the argument gets converted, not because the integer constant (i.e. after replacement) did not have a type, i.e. the Now, yes, in Rust there is type inference for integer literals without a suffix, which is what you want to use here to get some convenience back. But note that you are forced to pick a type and cast when using |
Input C/C++ Header
Bindgen Invocation
Actual Results
Expected Results
It would be better to generate something like
and to expect users to use
MYCONST!()
instead ofMYCONST
.Reasoning
Constants using
#define
in a C header file do not have a type. They are inserted by the preprocessor as a literal where needed. Translating them to a Rustconst
with a type (u32
,i32
, or others) may lead to unexpected results. For example,i32
can be interchaged withstd::os::raw::c_int
on most platforms. But code that relies on that will not be portable. See discussion on Rust Users Forum "Interfacing C code with bindgen: #define and types".Migration
Maybe it can be made possible to enable this new described behavior with an option that is not enabled by default; or the generated
macro_rules!
s could be created in addition to theconst
s (unless being switched off by an option).The text was updated successfully, but these errors were encountered: