Skip to content

Commit

Permalink
fix: struct offset position
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyuang committed Oct 21, 2023
1 parent 0dc4483 commit 3332e32
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ use define::{number_to_data_type, DataType, FFIParams, OpenParams, RsArgsValue};
use napi::bindgen_prelude::*;
use utils::{
calculate_layout, create_array_from_pointer, get_data_type_size_align,
get_js_function_call_value, js_array_to_number_array, js_array_to_string_array,
js_nunmber_to_i32, js_string_to_string, js_unknown_to_data_type, rs_array_to_js_array, ArrayType,
get_js_function_call_value, get_rs_value_size_align, js_array_to_number_array,
js_array_to_string_array, js_nunmber_to_i32, js_string_to_string, js_unknown_to_data_type,
rs_array_to_js_array, ArrayType,
};

use indexmap::IndexMap;
Expand Down Expand Up @@ -311,9 +312,12 @@ fn load(
};
}
RsArgsValue::Object(val) => {
let (size, align) = calculate_layout(&val);
let layout = if size > 0 && align > 0 {
Layout::from_size_align(size, 4).unwrap()
let (size, _) = calculate_layout(&val);

let layout = if size > 0 {
let (_, first_field) = val.get_index(0).unwrap();
let (_, align) = get_rs_value_size_align(first_field);
Layout::from_size_align(size, align).unwrap()
} else {
Layout::new::<i32>()
};
Expand Down
29 changes: 29 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,35 @@ pub fn calculate_layout(map: &IndexMap<String, RsArgsValue>) -> (usize, usize) {
(size, align)
}

pub fn get_rs_value_size_align(val: &RsArgsValue) -> (usize, usize) {
return match val {
RsArgsValue::I32(_) => (std::mem::size_of::<i32>(), std::mem::align_of::<i32>()),
RsArgsValue::Boolean(_) => (std::mem::size_of::<bool>(), std::mem::align_of::<bool>()),
RsArgsValue::String(_) => (
std::mem::size_of::<*const c_char>(),
std::mem::align_of::<*const c_char>(),
),
RsArgsValue::Double(_) => (
std::mem::size_of::<c_double>(),
std::mem::align_of::<c_double>(),
),
RsArgsValue::StringArray(_) => (
std::mem::size_of::<*const *const c_char>(),
std::mem::align_of::<*const *const c_char>(),
),
RsArgsValue::DoubleArray(_) => (
std::mem::size_of::<*const c_double>(),
std::mem::align_of::<*const c_double>(),
),
RsArgsValue::I32Array(_) => (
std::mem::size_of::<*const c_int>(),
std::mem::align_of::<*const c_int>(),
),
_ => {
panic!("get_rs_value_size_align error")
}
};
}
pub fn get_data_type_size_align(data_type: DataType) -> (usize, usize) {
return match data_type {
DataType::I32 => (std::mem::size_of::<i32>(), std::mem::align_of::<i32>()),
Expand Down

0 comments on commit 3332e32

Please sign in to comment.