PerlFFI / FFI-Platypus

Write Perl bindings to non-Perl libraries with FFI. No XS required.
89 stars 23 forks source link

Passing an empty array into a pointer argument doesn't appear to include the zero termination. #385

Closed plicease closed 1 year ago

plicease commented 1 year ago

Consider:

#include <stdlib.h>

int
array_sum(const int *a) {
  int i, sum;
  if(a == NULL)
    return -1;
  for(i=0, sum=0; a[i] != 0; i++)
    sum += a[i];
  return sum;
}
use strict;
use warnings;
use FFI::Platypus 2.00;

my $ffi = FFI::Platypus->new(
  api => 2,
  lib => './array_sum.so',
);

$ffi->attach( array_sum => ['int*'] => 'int' );

print array_sum(undef), "\n";   # -1
print array_sum([]), "\n";      # 0
print array_sum([1,2,3]), "\n"; #

output:

$ perl array_sum.pl 
-1
-1996961152
6

should be:

$ perl array_sum.pl 
-1
0
6
plicease commented 1 year ago

This may not actually be a bug. I think we only put the terminating NULL for string arrays. I think the rationale was that having 0 as a terminating value was too arbitrary.