Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
arguments for ctypes function
  • Loading branch information
arihant2math committed Mar 24, 2025
commit 503aa31f4629fc24005fd1cf21466bc56b34e8e9
67 changes: 64 additions & 3 deletions vm/src/stdlib/ctypes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub(crate) mod _ctypes {
use super::base::PyCSimple;
use crate::builtins::PyTypeRef;
use crate::class::StaticType;
use crate::function::{Either, OptionalArg};
use crate::function::{Either, FuncArgs, OptionalArg};
use crate::stdlib::ctypes::library;
use crate::{AsObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine};
use crossbeam_utils::atomic::AtomicCell;
Expand Down Expand Up @@ -125,11 +125,12 @@ pub(crate) mod _ctypes {
"d" | "g" => mem::size_of::<c_double>(),
"?" | "B" => mem::size_of::<c_uchar>(),
"P" | "z" | "Z" => mem::size_of::<usize>(),
"O" => mem::size_of::<PyObjectRef>(),
_ => unreachable!(),
}
}

const SIMPLE_TYPE_CHARS: &str = "cbBhHiIlLdfguzZPqQ?";
const SIMPLE_TYPE_CHARS: &str = "cbBhHiIlLdfguzZPqQ?O";

pub fn new_simple_type(
cls: Either<&PyObjectRef, &PyTypeRef>,
Expand Down Expand Up @@ -219,9 +220,14 @@ pub(crate) mod _ctypes {
#[pyfunction(name = "POINTER")]
pub fn pointer(_cls: PyTypeRef) {}

#[pyfunction]
#[pyfunction(name = "pointer")]
pub fn pointer_fn(_inst: PyObjectRef) {}

#[pyfunction]
fn _pointer_type_cache() -> PyObjectRef {
todo!()
}

#[cfg(target_os = "windows")]
#[pyfunction(name = "_check_HRESULT")]
pub fn check_hresult(_self: PyObjectRef, hr: i32, _vm: &VirtualMachine) -> PyResult<i32> {
Expand All @@ -244,6 +250,24 @@ pub(crate) mod _ctypes {
}
}

#[pyfunction]
fn byref(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// TODO: RUSTPYTHON
return Err(vm.new_value_error("not implemented".to_string()));
}

#[pyfunction]
fn alignment(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// TODO: RUSTPYTHON
return Err(vm.new_value_error("not implemented".to_string()));
}

#[pyfunction]
fn resize(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// TODO: RUSTPYTHON
return Err(vm.new_value_error("not implemented".to_string()));
}

#[pyfunction]
fn get_errno() -> i32 {
errno::errno().0
Expand All @@ -253,4 +277,41 @@ pub(crate) mod _ctypes {
fn set_errno(value: i32) {
errno::set_errno(errno::Errno(value));
}

#[cfg(windows)]
#[pyfunction]
fn get_last_error() -> PyResult<u32> {
Ok(unsafe { windows_sys::Win32::Foundation::GetLastError() })
}

#[cfg(windows)]
#[pyfunction]
fn set_last_error(value: u32) -> PyResult<()> {
unsafe { windows_sys::Win32::Foundation::SetLastError(value) };
Ok(())
}

#[pyattr]
fn _memmove_addr(_vm: &VirtualMachine) -> usize {
let f = libc::memmove;
f as usize
}

#[pyattr]
fn _memset_addr(_vm: &VirtualMachine) -> usize {
let f = libc::memset;
f as usize
}

#[pyattr]
fn _string_at_addr(_vm: &VirtualMachine) -> usize {
let f = libc::strnlen;
f as usize
}

#[pyattr]
fn _cast_addr(_vm: &VirtualMachine) -> usize {
// TODO: RUSTPYTHON
return 0;
}
}
45 changes: 29 additions & 16 deletions vm/src/stdlib/ctypes/function.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::builtins::{PyStr, PyTupleRef, PyTypeRef};
use crate::class::StaticType;
use crate::convert::ToPyObject;
use crate::function::FuncArgs;
use crate::stdlib::ctypes::array::PyCArray;
use crate::stdlib::ctypes::PyCData;
use crate::stdlib::ctypes::base::{PyCSimple, ffi_type_from_str};
use crate::types::{Callable, Constructor};
Expand All @@ -17,6 +17,7 @@ use std::fmt::Debug;

#[derive(Debug)]
pub struct Function {
args: Vec<Type>,
// TODO: no protection from use-after-free
pointer: CodePtr,
cif: Cif,
Expand All @@ -35,21 +36,20 @@ impl Function {
ret_type: &Option<PyTypeRef>,
vm: &VirtualMachine,
) -> PyResult<Self> {
dbg!("Start load");
// map each arg to a PyCSimple
let args = args
.iter()
.map(|arg| {
dbg!();
if arg.obj_type().is_subclass(PyCSimple::static_type().into(), vm)? {
dbg!();
let typ = arg.get_attr("_type_", vm)?;
let typ = typ.downcast_ref::<PyStr>().unwrap();
let converted = ffi_type_from_str(typ.as_str());
if let Some(arg) = arg.payload_if_subclass::<PyCSimple>(vm) {
dbg!(arg);
let converted = ffi_type_from_str(&arg._type_);
dbg!(&converted);
match converted {
Some(t) => Ok(t),
None => Err(vm.new_type_error(format!(
"Invalid type: {}",
typ.as_str()
"Invalid type"
// TODO: add type name
))),
}
} else {
Expand All @@ -73,8 +73,10 @@ impl Function {
}
None => Type::c_int(),
};
let cif = Cif::new(args, return_type);
let cif = Cif::new(args.clone(), return_type);
dbg!();
Ok(Function {
args,
cif,
pointer: code_ptr,
})
Expand All @@ -85,19 +87,30 @@ impl Function {
args: Vec<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
dbg!("Start call");
let args = args
.into_iter()
.map(|arg| {
if let Some(data) = arg.downcast_ref::<PyCSimple>() {
dbg!(&data);
todo!("HANDLE ARGUMENTS")
} else {
Err(vm.new_type_error("Expected a ctypes simple type".to_string()))
.enumerate()
.map(|(count, arg)| {
dbg!("Arg iter", &arg);
dbg!(&arg);
if let Some(d) = arg.payload_if_subclass::<PyCSimple>(vm) {
dbg!(d);
dbg!(&d._type_);
unsafe {
dbg!(d.value.as_ptr().as_ref().unwrap());
}
return Ok(d.to_arg(self.args[count].clone(), vm).unwrap());
}
if let Some(d) = arg.payload_if_subclass::<PyCArray>(vm) {
dbg!(d);
}
Err(vm.new_type_error("Expected a ctypes simple type".to_string()))
})
.collect::<PyResult<Vec<Arg>>>()?;
// TODO: FIX return type
let result: i32 = unsafe { self.cif.call(self.pointer, &args) };
dbg!("Almost end call");
Ok(vm.ctx.new_int(result).into())
}
}
Expand Down