Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions crates/vm/src/stdlib/_ctypes/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1292,8 +1292,13 @@ struct Argument {
keep: Option<PyObjectRef>, // Object to keep alive during call
}

/// Out buffers for paramflags OUT parameters
type OutBuffers = Vec<(usize, PyObjectRef)>;
/// Values returned for paramflags OUT and IN/OUT parameters.
enum OutValue {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check this is a good design

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

at least not bad at the moment

Out(PyObjectRef),
InOut(PyObjectRef),
}

type OutBuffers = Vec<OutValue>;

/// Get buffer address from a ctypes object
fn get_buffer_addr(obj: &PyObject) -> Option<usize> {
Expand Down Expand Up @@ -1409,7 +1414,7 @@ fn build_callargs_with_paramflags(
keep: None,
value: CArgValue::pointer(addr),
});
out_buffers.push((param_idx, buffer));
out_buffers.push(OutValue::Out(buffer));
} else {
// IN or IN|OUT: get from caller args or default
let arg = if caller_arg_idx < args.args.len() {
Expand All @@ -1423,7 +1428,7 @@ fn build_callargs_with_paramflags(

if is_out {
// IN|OUT: track for return
out_buffers.push((param_idx, arg.clone()));
out_buffers.push(OutValue::InOut(arg.clone()));
}
let (value, keep) = arg_type.convert_object(arg, vm)?;
arguments.push(Argument { value, keep });
Expand Down Expand Up @@ -1661,13 +1666,13 @@ fn pycdata_from_ffi_result(
}

/// Extract values from OUT buffers
fn extract_out_values(
out_buffers: Vec<(usize, PyObjectRef)>,
vm: &VirtualMachine,
) -> Vec<PyObjectRef> {
fn extract_out_values(out_buffers: &[OutValue], vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
out_buffers
.into_iter()
.map(|(_, buffer)| buffer.get_attr("value", vm).unwrap_or(buffer))
.iter()
.map(|value| match value {
OutValue::Out(buffer) => vm.call_method(buffer, "__ctypes_from_outparam__", ()),
OutValue::InOut(buffer) => Ok(buffer.clone()),
})
.collect()
}

Expand Down Expand Up @@ -1716,7 +1721,10 @@ fn build_result(
return result.map_or_else(|| Ok(vm.ctx.none()), Ok);
}

let out_values = extract_out_values(out_buffers, vm);
// OUT parameters replace the raw result. Release it before conversion,
// which can invoke user-defined methods.
drop(result);
let out_values = extract_out_values(&out_buffers, vm)?;
Ok(match <[PyObjectRef; 1]>::try_from(out_values) {
Ok([single]) => single,
Err(v) => PyTuple::new_ref(v, &vm.ctx).into(),
Expand Down
Loading