2016-08-18 45 views
2

我发现了类似的问题Compile-time generic type size check,但没有收到任何答案。在编译时检查指针大小

问题是通过FFI +不安全,与其他编程语言合作, 我想确保mem::size_of::<*mut T>()具有适当的大小。 我发现在互联网这样的static_assert宏:

macro_rules! static_assert { 
    (type $t:ty;) => (
     type __StaticAssert = $t; 
    ); 

    (type $t:ty; $e:expr $(, $ee:expr)*) => (
     static_assert!(type ($t, [i8; 0 - ((false == ($e)) as usize)]); $($ee),*); 
    ); 

    ($e:expr $(, $ee:expr)*) => (
     static_assert!(type [i8; 0 - ((false == ($e)) as usize)]; $($ee),*); 
    ); 
} 

static_assert!(2 == 2); 

它的工作原理,但如果我用mem::size_of::<*const f64>()内宏观所有失败 因为,:calls in constants are limited to struct and enum constructors, 任何想法如何计算size_of*const f64在编译时?

+2

如果另一个问题没有收到答案,打开副本并不是一种方式,如果您想增加另一个问题的可见性,请考虑添加[bounty](http://stackoverflow.com/help/)赏金)它 –

+2

它看起来不是一个完整的重复给我,你能展开这个问题不同于[这个相关的问题](http://stackoverflow.com/questions/30330519/compile-time-generic-type-大小检查)你链接? –

+2

'mem :: size_of'在编译时尚未评估。等一年,故事可能会改变(但也许不会,谁知道?)。 – Veedrac

回答

2

对于指针,有一个可以检查的配置标志。你可以这样做强制编译时错误:

#[cfg(not(target_pointer_width = "64"))] 
const ERROR:() = "Your pointers are too small. Please try again with a more expensive computer."; 

一般有“蜕变绝招”:断言在编译时的东西的大小,它蜕变的东西这是众所周知的有正确的大小在一个死的功能。例如:

#[allow(dead_code)] 
fn _assert_pointers_are_64bits() { 
    unsafe { 
     ::std::mem::transmute::<*const f64, [u8; 8]>(panic!()); 
    } 
} 

这些技巧将不得不这样做,直到size_of制成一个const FN。

+0

谢谢。你能在这里解释什么类型的意思感叹号 - >!'? – fghj

+1

这意味着它是一个[发散函数](https://doc.rust-lang.org/reference.html#diverging-functions)。 – antoyo

+0

为了记录,我删除了@ user1034749询问的' - >!',由于[编译器错误](https://github.com/rust-lang/rust/issues/35849)。 – durka42