Skip to content

Commit 4924b44

Browse files
committed
Simplify Gd::from_sys_init_opt() -- from_obj_sys() instead of from_sys_init()
1 parent 8d9ff8b commit 4924b44

File tree

1 file changed

+9
-19
lines changed

1 file changed

+9
-19
lines changed

godot-core/src/obj/gd.rs

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -468,30 +468,20 @@ impl<T: GodotClass> GodotFfi for Gd<T> {
468468
impl<T: GodotClass> Gd<T> {
469469
pub unsafe fn from_sys_init_opt(init_fn: impl FnOnce(sys::GDNativeTypePtr)) -> Option<Self> {
470470
// Note: see _call_native_mb_ret_obj() in godot-cpp, which does things quite different (e.g. querying the instance binding).
471-
// This method could be simplified if it would modify the object directly and not wrap from_sys_init().
472471

473-
// Much elegant
474-
let mut is_null = false;
475-
let outer_fn = |return_ptr| {
476-
// ptr has type GDNativeTypePtr = GDNativeObjectPtr* = OpaqueObject* = Object**
477-
// (in other words, the opaque struct encodes an Object*; or, the type-ptr contains the _address_ of an object-ptr)
478-
let object_ptr_ptr = return_ptr as *mut sys::GDNativeObjectPtr;
479-
*object_ptr_ptr = ptr::null_mut();
472+
// return_ptr has type GDNativeTypePtr = GDNativeObjectPtr* = OpaqueObject* = Object**
473+
// (in other words, the type-ptr contains the _address_ of an object-ptr).
474+
let mut object_ptr: sys::GDNativeObjectPtr = ptr::null_mut();
475+
let return_ptr: *mut sys::GDNativeObjectPtr = ptr::addr_of_mut!(object_ptr);
480476

481-
init_fn(return_ptr);
477+
init_fn(return_ptr as sys::GDNativeTypePtr);
482478

483-
// we don't need to know if Object** is null, but if Object* (modified through Object**) is null.
484-
if (*object_ptr_ptr).is_null() {
485-
is_null = true;
486-
}
487-
};
488-
489-
let gd = Self::from_sys_init(outer_fn);
490-
if is_null {
491-
std::mem::forget(gd); // null Gd is not a valid state which destructor should handle
479+
// We don't need to know if Object** is null, but if Object* is null; return_ptr has the address of a local (never null).
480+
if object_ptr.is_null() {
492481
None
493482
} else {
494-
Some(gd)
483+
let obj = Gd::from_obj_sys(object_ptr); // equivalent to Gd::from_sys(return_ptr)
484+
Some(obj)
495485
}
496486
}
497487
}

0 commit comments

Comments
 (0)