Skip to content

Commit

Permalink
feat: support function as params skip ci
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyuang committed Oct 25, 2023
1 parent 2f11b74 commit 1776184
Show file tree
Hide file tree
Showing 6 changed files with 394 additions and 319 deletions.
2 changes: 2 additions & 0 deletions cpp/sum.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <iostream>
#include <string>
#include <vector>
#include <xlocale/_stdio.h>

extern "C" int sum(int a, int b) { return a + b; }

Expand Down Expand Up @@ -98,6 +99,7 @@ typedef void (*FunctionPointer)(double a);
extern "C" void callFunction(FunctionPointer func) {
printf("callFunction");
double a = 100.11;
// bool a = false;
// char *a = "Hello, World!";
// char *str = (char *)malloc(14 * sizeof(char));
// strcpy(str, "Hello, World!");
Expand Down
1 change: 1 addition & 0 deletions scripts/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export type ArrayConstructorOptions<T extends DataType> = {

export type FuncConstructorOptions<T extends DataType> = {
paramsType: Array<DataFieldType<T>>
retType: DataFieldType<T>
}

export function arrayConstructor<T extends DataType>(options: ArrayConstructorOptions<T>): ArrayConstructorOptions<T>
Expand Down
30 changes: 30 additions & 0 deletions src/ffi_macro.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
macro_rules! match_args_len {
($args_len:expr, $func_args_type:expr, $js_function:expr, $env:expr, $($num:literal => $closure:ident, $($arg:ident),*),*) => {
match $args_len {
$(
$num => {
use libffi::high::$closure;
let lambda = |$($arg: *mut c_void),*| {
let value: Vec<JsUnknown> = (0..$args_len)
.map(|index| {
let c_param = match index {
$(
idx if idx == index => $arg,
)*
_ => unreachable!(),
};
let arg_type = $func_args_type.get_element::<JsUnknown>(index).unwrap();
let param = get_js_function_call_value($env, arg_type, c_param);
param
})
.collect();
$js_function.call(None, &value).unwrap();
};
let closure = Box::into_raw(Box::new($closure::new(&lambda)));
return std::mem::transmute((*closure).code_ptr());
}
)*
_ => panic!("func_args get array error"),
}
};
}
Loading

0 comments on commit 1776184

Please sign in to comment.