以下内容(如果将MCVE编译为称为cdyliblibffitest,则需要libc作为依赖项)演示了此问题:

use libc::{c_char, c_void, size_t};
use std::ffi::CString;
use std::mem;
use std::slice;

#[repr(C)]
#[derive(Clone)]
pub struct Array {
    pub data: *const c_void,
    pub len: size_t,
}

#[no_mangle]
pub unsafe extern "C" fn bar() -> Array {
    let v = vec![
        CString::new("Hi There").unwrap().into_raw(),
        CString::new("Hi There").unwrap().into_raw(),
    ];
    v.into()
}

#[no_mangle]
pub extern "C" fn drop_word_array(arr: Array) {
    if arr.data.is_null() {
        return;
    }
    // Convert incoming data to Vec so we own it
    let mut f: Vec<c_char> = arr.into();
    // Deallocate the underlying c_char data by reconstituting it as a CString
    let _: Vec<CString> = unsafe { f.iter_mut().map(|slice| CString::from_raw(slice)).collect() };
}

// Transmute to array for FFI
impl From<Vec<*mut c_char>> for Array {
    fn from(sl: Vec<*mut c_char>) -> Self {
        let array = Array {
            data: sl.as_ptr() as *const c_void,
            len: sl.len() as size_t,
        };
        mem::forget(sl);
        array
    }
}

// Reconstitute from FFI
impl From<Array> for Vec<c_char> {
    fn from(arr: Array) -> Self {
        unsafe { slice::from_raw_parts_mut(arr.data as *mut c_char, arr.len).to_vec() }
    }
}

我以为通过将传入的Array重构为片,将其所有权作为Vec,然后将元素重构为CString,可以释放任何分配的内存,但是显然我在做错什么。执行此Python脚本告诉我,它正在尝试释放未分配的指针:python(85068,0x10ea015c0) malloc: *** error for object 0x7ffdaa512ca1: pointer being freed was not allocated
import sys
import ctypes
from ctypes import c_void_p, Structure, c_size_t, cast, POINTER, c_char_p

class _FFIArray(Structure):
    """
    Convert sequence of structs to C-compatible void array

    """
    _fields_ = [("data", c_void_p),
                ("len", c_size_t)]


def _arr_to_wordlist(res, _func, _args):
    ls = cast(res.data, POINTER(c_char_p * res.len))[0][:]
    print(ls)
    _drop_wordarray(res)


prefix = {"win32": ""}.get(sys.platform, "lib")
extension = {"darwin": ".dylib", "win32": ".dll"}.get(sys.platform, ".so")
lib = ctypes.cdll.LoadLibrary(prefix + "ffitest" + extension)

lib.bar.argtypes = ()
lib.bar.restype = _FFIArray
lib.bar.errcheck = _arr_to_wordlist
_drop_wordarray = lib.drop_word_array

if __name__ == "__main__":
    lib.bar()

最佳答案

好吧,那是一个有趣的经历。

您的最大的问题是以下转换:

impl From<Array> for Vec<c_char> {
    fn from(arr: Array) -> Self {
        unsafe { slice::from_raw_parts_mut(arr.data as *mut c_char, arr.len).to_vec() }
    }
}

您将从FFI边界中产生的内容作为字符串数组(即*mut *mut c_char)开始。由于某种原因,您突然决定它是Vec<c_char>,而不是Vec<*const c_char>转换所期望的CString。那是UB#1-这是您的免税使用原因。

由于类型之间不断变化,不必要地费解的转换使事情变得更加困惑。如果您的FFI边界是Vec<CString>,为什么将 yield 分成两个单独的调用?这确实是在发生灾难,这是在呼唤灾难。

考虑以下:
impl From<Array> for Vec<CString> {
    fn from(arr: Array) -> Self {
        unsafe {
          slice::from_raw_parts(
            arr.data as *mut *mut c_char,
            arr.len
          )
            .into_iter().map(|r| CString::from_raw(*r))
            .collect()
        }
    }
}

这为您提供了一步式FFI边界转换(方法中无需第二个unsafe块),干净的类型且无泄漏。

关于python - 尝试释放CString数组时发生内存泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58061938/

10-14 10:34