1616// under the License.
1717
1818use std:: collections:: HashMap ;
19- use std:: ffi:: { c_void , CStr , CString } ;
19+ use std:: ffi:: { CStr , CString } ;
2020use std:: sync:: Arc ;
2121
2222use arrow:: array:: { new_null_array, RecordBatch , RecordBatchReader } ;
@@ -39,7 +39,6 @@ use datafusion::prelude::*;
3939use datafusion_ffi:: table_provider:: FFI_TableProvider ;
4040use futures:: { StreamExt , TryStreamExt } ;
4141use pyo3:: exceptions:: PyValueError ;
42- use pyo3:: ffi;
4342use pyo3:: prelude:: * ;
4443use pyo3:: pybacked:: PyBackedStr ;
4544use pyo3:: types:: { PyCapsule , PyList , PyTuple , PyTupleMethods } ;
@@ -967,28 +966,12 @@ impl PyDataFrame {
967966 } ;
968967 let reader: Box < dyn RecordBatchReader + Send > = Box :: new ( reader) ;
969968
970- let stream = Box :: new ( FFI_ArrowArrayStream :: new ( reader) ) ;
971- let stream_ptr = Box :: into_raw ( stream) ;
972- debug_assert ! (
973- !stream_ptr. is_null( ) ,
974- "ArrowArrayStream pointer should never be null" ,
975- ) ;
969+ let stream = FFI_ArrowArrayStream :: new ( reader) ;
976970 // The returned capsule allows zero-copy hand-off to PyArrow. When
977- // PyArrow imports the capsule it assumes ownership of the stream.
978- let capsule = unsafe {
979- ffi:: PyCapsule_New (
980- stream_ptr as * mut c_void ,
981- ARROW_STREAM_NAME . as_ptr ( ) ,
982- None ,
983- )
984- } ;
985- if capsule. is_null ( ) {
986- unsafe { drop ( Box :: from_raw ( stream_ptr) ) } ;
987- Err ( PyErr :: fetch ( py) . into ( ) )
988- } else {
989- let any = unsafe { Bound :: from_owned_ptr ( py, capsule) } ;
990- Ok ( any. downcast_into :: < PyCapsule > ( ) . unwrap ( ) )
991- }
971+ // PyArrow imports the capsule it assumes ownership of the stream and
972+ // nulls out the capsule's internal pointer so the destructor does not
973+ // free it twice.
974+ PyCapsule :: new ( py, stream, Some ( ARROW_STREAM_NAME ) ) . map_err ( Into :: into)
992975 }
993976
994977 fn execute_stream ( & self , py : Python ) -> PyDataFusionResult < PyRecordBatchStream > {
0 commit comments