@@ -564,7 +564,7 @@ public Tensor(Operation op, int value_index, TF_DataType dtype)
564564 _id = ops . uid ( ) ;
565565 }
566566
567- private bool _isPinnedArray = false ;
567+ private bool _isPinnedArray => _deallocatorArgs . gc_handle != IntPtr . Zero ;
568568
569569 /// <summary>
570570 /// Creates a new tensor from the given array without copying memory. The array is pinned down and the pointer passed on.
@@ -620,12 +620,11 @@ protected unsafe IntPtr CreateTensorWithoutCopying(TF_DataType dt, long[] shape,
620620
621621 // get a handle to the pinned array which we will pass on to the tensor computation engine to use
622622 var gcHandle = GCHandle . Alloc ( data , GCHandleType . Pinned ) ;
623- _isPinnedArray = true ;
624623 _deallocatorArgs = new DeallocatorArgs ( ) { gc_handle = GCHandle . ToIntPtr ( gcHandle ) } ;
625624 // Free the original buffer and set flag
626625 Deallocator deallocator = ( IntPtr ptr , IntPtr len , ref DeallocatorArgs args ) =>
627626 {
628- if ( args . deallocator_called )
627+ if ( args . deallocator_called || args . gc_handle == IntPtr . Zero )
629628 return ;
630629 // note: since the ptr given to tensorflow is just the addr of the pinned object we can not directly free it! we need to free the gcHandle instead
631630 GCHandle . FromIntPtr ( args . gc_handle ) . Free ( ) ;
@@ -638,6 +637,6 @@ protected unsafe IntPtr CreateTensorWithoutCopying(TF_DataType dt, long[] shape,
638637 return TF_NewTensor ( dt , shape , shape . Length , gcHandle . AddrOfPinnedObject ( ) + start * element_size , ( UIntPtr ) ( count * element_size ) , deallocator , ref _deallocatorArgs ) ;
639638 }
640639
641- private DeallocatorArgs _deallocatorArgs = new DeallocatorArgs ( ) ;
640+ private DeallocatorArgs _deallocatorArgs = new DeallocatorArgs ( ) { gc_handle = IntPtr . Zero } ;
642641 }
643642}
0 commit comments