gemini-code-assist[bot] commented on code in PR #407:
URL: https://github.com/apache/tvm-ffi/pull/407#discussion_r2683482496
##########
python/tvm_ffi/cython/function.pxi:
##########
@@ -889,6 +889,27 @@ cdef class Function(Object):
def __cinit__(self) -> None:
self.c_release_gil = _RELEASE_GIL_BY_DEFAULT
+ def __init__(self, func: Callable[..., Any]) -> None:
+ """Initialize a Function from a Python callable.
+
+ This constructor allows creating a `tvm_ffi.Function` directly
+ from a Python function or another `tvm_ffi.Function` instance.
+
+ Parameters
+ ----------
+ func : Callable[..., Any]
+ The Python callable to wrap.
+ """
+ cdef TVMFFIObjectHandle chandle = NULL
+ if not callable(func):
+ raise TypeError(f"func must be callable, got {type(func)}")
+ if isinstance(func, Function):
+ chandle = (<Object>func).chandle
+ TVMFFIObjectIncRef(chandle)
+ else:
+ _convert_to_ffi_func_handle(func, &chandle)
+ self.chandle = chandle
Review Comment:

Calling `__init__` on an already-initialized `tvm_ffi.Function` object will
cause a memory leak. The current implementation overwrites `self.chandle`
without decrementing the reference count of the previously held handle. To
prevent this and enforce that `__init__` acts as a one-time constructor, you
should add a check to ensure the object is not already initialized.
```
if self.chandle != NULL:
raise TypeError("A tvm_ffi.Function object can only be
initialized once.")
cdef TVMFFIObjectHandle chandle = NULL
if not callable(func):
raise TypeError(f"func must be callable, got {type(func)}")
if isinstance(func, Function):
chandle = (<Object>func).chandle
TVMFFIObjectIncRef(chandle)
else:
_convert_to_ffi_func_handle(func, &chandle)
self.chandle = chandle
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]