2017-07-31 97 views
0

,當我試圖導入GetBinaryTypeA功能:段錯誤調用GetBinaryTypeA

use std::ffi::CString; 

use ::std::os::raw::{c_char, c_ulong}; 
extern { fn GetBinaryTypeA(s: *const c_char, out: *mut c_ulong) -> i32; } 

fn main() { 
    let path = "absolute/path/to/bin.exe"; 

    let cpath = CString::new(path).unwrap(); 
    let mut out: c_ulong = 0; 

    println!("{:?}", cpath); 
    unsafe { GetBinaryTypeA(cpath.as_ptr(), out as *mut c_ulong); } 
    println!("{:?}", cpath); 
} 

輸出:

error: process didn't exit successfully: `target\debug\bin_deploy.exe` (exit code: 3221225477) 
Process finished with exit code -1073741819 (0xC0000005) 

如果我設置了無效的路徑,然後它執行成功和GetLastError()回報2(「系統不能找到指定的文件「),所以它看起來像導入的功能。

我使用kernel32-sys箱子收到了同樣的錯誤。錯誤在哪裏呢?

+0

沒有* 「段錯誤」 *在Windows中。請儘量表達您的問題。 – IInspectable

+1

@IInspectable你爲什麼不編輯問題來糾正這個問題? – Boiethios

+0

@Boiethios:我不能重現這個問題,我不知道確切的錯誤信息。 '0xC0000005'看起來像訪問衝突,但我不知道,Rust運行時如何報告這一點。既然你大概可以在你的機器上重現問題,爲什麼不自己提出編輯? – IInspectable

回答

2

您正在將值0轉換爲指針。在當今使用的絕大多數計算機上,值爲0的指針被稱爲NULL。因此,您正嘗試寫入NULL指針,從而導致崩潰。

你要寫入值的地址:

&mut out as *mut c_ulong 

這甚至不需要投:

unsafe { 
    GetBinaryTypeA(cpath.as_ptr(), &mut out); 
} 
+1

是的,這是有效的。謝謝! – Alex

+0

有關生鏽指針的更多信息:https://doc.rust-lang.org/std/primitive.pointer.html – Alex