use hao::{
dotnet::{
entries::Method,
il::{Emitter, Instruction, OpCode},
module::{ModuleKind, TargetRuntime},
signature::{MethodSig, TypeSig},
},
Module,
};
use hao_runtime::Runtime;
fn calc_module() -> Module {
let mut module = Module::new(
"Plain",
ModuleKind::Dll,
TargetRuntime::NetCoreImplementation(9),
);
let calc = module.add_static_class("Plain", "Calc").unwrap();
let signature = |params| MethodSig::new_static(TypeSig::INT32, vec![TypeSig::INT32; params]);
calc.add_method(
Method::public_static("Add", signature(2)).with_body(Emitter::build(|e| {
e.ldarg(0).ldarg(1).op(OpCode::Add).ret();
})),
);
calc.add_method(
Method::public_static("Double", signature(1)).with_body(Emitter::build(|e| {
e.ldarg(0).ldarg(0).op(OpCode::Add).ret();
})),
);
module
}
fn main() -> hao_runtime::Result<()> {
let runtime = Runtime::coreclr()?;
let module = calc_module();
module
.find_method("Plain.Calc", "Double")
.unwrap()
.edit_body(|body| {
body.instructions = vec![
Instruction::ldarg(0),
Instruction::ldc_i4(10),
Instruction::simple(OpCode::Mul),
Instruction::ret(),
];
});
runtime.load_module(&module)?;
match runtime.function_pointer("Plain", "Plain.Calc", "Add") {
Err(e) => println!("function_pointer(Add): {}", e),
Ok(_) => println!("function_pointer(Add): unexpectedly succeeded"),
}
let add: extern "C" fn(i32, i32) -> i32 =
unsafe { std::mem::transmute(runtime.method_pointer("Plain", "Plain.Calc", "Add")?) };
let double: extern "C" fn(i32) -> i32 =
unsafe { std::mem::transmute(runtime.method_pointer("Plain", "Plain.Calc", "Double")?) };
println!("Calc.Add(40, 2) = {}", add(40, 2));
println!("Calc.Double(5) = {} (patched to times 10)", double(5));
Ok(())
}