2016-08-18 43 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