Skip to content

Commit 97374d3

Browse files
committed
fix: Clean up
1 parent 8e791d1 commit 97374d3

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

src/c2pa/c2pa.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1319,34 +1319,33 @@ def from_callback(
13191319

13201320
# Create a wrapper callback that handles errors and memory management
13211321
def wrapped_callback(context, data_ptr, data_len, signed_bytes_ptr, signed_len):
1322+
# Returns 0 on error as this case is handled in the native code gracefully
13221323
try:
13231324
if not data_ptr or data_len <= 0:
13241325
return 0 # Error: invalid input
13251326

13261327
# Convert C pointer to Python bytes
13271328
data = bytes(data_ptr[:data_len])
1328-
13291329
if not data:
1330-
return 0 # Error: empty data
1330+
return 0 # Error: empty data, native code will handle it!
13311331

13321332
# Call the user's callback
13331333
signature = callback(data)
1334-
13351334
if not signature:
1336-
return 0 # Error: empty signature
1335+
return 0 # Error: empty signature, native code will handle that too!
13371336

13381337
# Copy the signature back to the C buffer
13391338
actual_len = min(len(signature), signed_len)
1340-
13411339
for i in range(actual_len):
13421340
signed_bytes_ptr[i] = signature[i]
13431341

1344-
return actual_len # Return the number of bytes written
1342+
# Native code expects the signed len to be returned, we oblige
1343+
return actual_len
13451344
except Exception as e:
13461345
print(
13471346
cls._error_messages['callback_error'].format(
13481347
str(e)), file=sys.stderr)
1349-
return 0 # Return 0 to indicate error
1348+
return 0
13501349

13511350
# Encode strings with error handling
13521351
try:
@@ -1358,10 +1357,11 @@ def wrapped_callback(context, data_ptr, data_len, signed_bytes_ptr, signed_len):
13581357
str(e)))
13591358

13601359
# Create the signer with the wrapped callback
1361-
# Store the callback as an instance attribute to keep it alive
1360+
# Store the callback as an instance attribute to keep it alive, as this prevents
1361+
# garbage colelction and lifetime issues.
13621362
signer_instance = cls.__new__(cls)
13631363
signer_instance._callback_cb = SignerCallback(wrapped_callback)
1364-
1364+
13651365
signer_ptr = _lib.c2pa_signer_create(
13661366
None, # context
13671367
signer_instance._callback_cb,
@@ -1380,7 +1380,7 @@ def wrapped_callback(context, data_ptr, data_len, signed_bytes_ptr, signed_len):
13801380
signer_instance._signer = signer_ptr
13811381
signer_instance._closed = False
13821382
signer_instance._error_messages = cls._error_messages
1383-
1383+
13841384
return signer_instance
13851385

13861386
def __enter__(self):

0 commit comments

Comments
 (0)