c_int32未正确传递给c函数

时间:2016-11-11 10:36:33

标签: python rust ctypes ffi

我在rust中有以下代码,仅检查数组是否包含低于1的值:

// src/lib.rs
extern crate libc;
use self::libc::int32_t;

#[no_mangle]
pub extern "C" fn rle_find_zero_lengths(array: &[int32_t], size: int32_t) -> int32_t {

    println!("Rust (C extern): {:?}", size);
    return find_zero_lengths(array, size);

}

pub fn find_zero_lengths(lengths: &[i32], size: int32_t) -> i32 {

    println!("Rust (pub fn): {:?}", size);
    for i in 0..(size - 1) {
        println!("{:?}, {:?}", i, lengths[i as usize]);
        if lengths[i as usize] < 1 {
            return 1;
        };
    }

    return 0;

}

#[cfg(test)]
mod rle_tests {
    use super::find_zero_lengths;

    #[test]
    fn test_find_zero_lengths() {

        let lengths = [0; 3];
        println!("{:?}", lengths);

        let actual_result = find_zero_lengths(&lengths, 3);

        assert_eq!(1, actual_result);
    }


    #[test]
    fn test_find_zero_lengths2() {

        let lengths = [1, 1, 2, 3];
        println!("{:?}", lengths);

        let actual_result = find_zero_lengths(&lengths, 3);

        assert_eq!(0, actual_result);

    }
}

这是我的Cargo.toml

[package]
name = "c_int_strange"
version = "0.1.0"
authors = ["Karl Dilkington"]

[dependencies]
libc = "0.2.17"

[lib]
crate-type = ["rlib", "dylib"]

这是我用来调用库的Python代码:

# c_int_strange.py
import sys, ctypes, os
from ctypes import c_char_p, c_uint32, Structure, POINTER, c_int32, c_size_t, pointer


prefix = {'win32': ''}.get(sys.platform, 'lib')
extension = {'darwin': '.dylib', 'win32': '.dll'}.get(sys.platform, '.so')
libpath = os.environ.get("LD_LIBRARY_PATH", "target/debug") + "/"
libpath = libpath + prefix + "c_int_strange" + extension
try:
    lib = ctypes.cdll.LoadLibrary(libpath)
except OSError:
    print("Library not found at " + libpath)


lib.rle_find_zero_lengths.argtypes = (POINTER(c_int32), c_int32, )
lib.rle_find_zero_lengths.restype = c_int32


lengths = [1, 2, 3, 4]
lengths_array = (c_int32 * len(lengths))(*lengths)

print("Python: len(lengths_array)): ", len(lengths_array))

contains_zero = lib.rle_find_zero_lengths(lengths_array, c_int32(len(lengths_array)))

现在,当我运行它时,我得到以下输出:

Python: len(lengths_array)):  4
Rust (extern C): 17583168
Rust (pub fn): 17583168
0, 1
1, 2
2, 3
3, 4
thread '<unnamed>' panicked at 'index out of bounds: the len is 4 but the index is 4', src/lib.rs:16
note: Run with `RUST_BACKTRACE=1` for a backtrace.
fatal runtime error: failed to initiate panic, error 5
fish: 'python strange_c_int.py' terminated by signal SIGABRT (Abort)

我做错了什么使我发送到C函数的int成为一些随机的其他值?

0 个答案:

没有答案