You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "eerhardt (via GitHub)" <gi...@apache.org> on 2023/05/10 02:50:10 UTC

[GitHub] [arrow] eerhardt commented on a diff in pull request #35496: GH-33856: [C#] Implement C Data Interface for C#

eerhardt commented on code in PR #35496:
URL: https://github.com/apache/arrow/pull/35496#discussion_r1189289825


##########
csharp/src/Apache.Arrow/C/CArrowArrayExporter.cs:
##########
@@ -0,0 +1,210 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+using System;
+using System.Runtime.InteropServices;
+using Apache.Arrow.Memory;
+
+namespace Apache.Arrow.C
+{
+    public static class CArrowArrayExporter
+    {
+        private unsafe delegate void ReleaseArrowArray(CArrowArray* cArray);
+
+        /// <summary>
+        /// Export an <see cref="IArrowArray"/> to a <see cref="CArrowArray"/>. Whether or not the
+        /// export succeeds, the original array becomes invalid. Clone an array to continue using it
+        /// after a copy has been exported.
+        /// </summary>
+        /// <param name="array">The array to export</param>
+        /// <param name="cArray">An allocated but uninitialized CArrowArray pointer.</param>
+        /// <example>
+        /// <code>
+        /// CArrowArray* exportPtr = CArrowArray.Create();
+        /// CArrowArrayExporter.ExportArray(array, exportPtr);
+        /// foreign_import_function(exportPtr);
+        /// </code>
+        /// </example>
+        public static unsafe void ExportArray(IArrowArray array, CArrowArray* cArray)
+        {
+            if (array == null)
+            {
+                throw new ArgumentNullException(nameof(array));
+            }
+            if (cArray == null)
+            {
+                throw new ArgumentNullException(nameof(cArray));
+            }
+            if (cArray->release != null)
+            {
+                throw new ArgumentException("Cannot export array to a struct that is already initialized.", nameof(cArray));
+            }
+
+            ExportedAllocationOwner allocationOwner = new ExportedAllocationOwner();
+            try
+            {
+                ConvertArray(allocationOwner, array.Data, cArray);
+                cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);

Review Comment:
   I think we can do this another way. If you add `[UnmanagedCallersOnly]` to the `private unsafe static void ReleaseArray(CArrowArray* cArray)` method, then this line should just be:
   
   ```suggestion
                   cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)&ReleaseArray;
   ```



##########
csharp/src/Apache.Arrow/Arrays/ArrowArrayFactory.cs:
##########
@@ -25,6 +25,8 @@ public static IArrowArray BuildArray(ArrayData data)
         {
             switch (data.DataType.TypeId)
             {
+                case ArrowTypeId.Null:

Review Comment:
   Can we add some tests for the Null array?



##########
csharp/src/Apache.Arrow/Memory/ExportedAllocationOwner.cs:
##########
@@ -0,0 +1,55 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+namespace Apache.Arrow.Memory
+{
+    internal sealed class ExportedAllocationOwner : INativeAllocationOwner, IDisposable
+    {
+        private readonly List<IntPtr> _pointers = new List<IntPtr>();
+        private int _allocationSize;
+
+        ~ExportedAllocationOwner()
+        {
+            Dispose();

Review Comment:
   This should implement the Disposable pattern.
   
   https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose



##########
csharp/src/Apache.Arrow/Arrays/ArrowArrayFactory.cs:
##########
@@ -25,6 +25,8 @@ public static IArrowArray BuildArray(ArrayData data)
         {
             switch (data.DataType.TypeId)
             {
+                case ArrowTypeId.Null:

Review Comment:
   We should also update 
   
   https://github.com/apache/arrow/blob/122fc86576b03ebd130e027200c5eda6a185d2ee/docs/source/status.rst?plain=1#L32-L35
   
   for this new functionality.
   
   We should also turn on this integration test as well:
   
   https://github.com/apache/arrow/blob/122fc86576b03ebd130e027200c5eda6a185d2ee/dev/archery/archery/integration/datagen.py#L1672-L1673
   
   



##########
csharp/src/Apache.Arrow/Memory/NativeMemoryManager.cs:
##########
@@ -64,20 +72,36 @@ public override void Unpin()
         protected override void Dispose(bool disposing)
         {
             // Only free once.
+            IntPtr ptr = Interlocked.Exchange(ref _ptr, IntPtr.Zero);
+            if (ptr != IntPtr.Zero)
+            {
+                _owner.Release(ptr, _offset, _length);
+            }
+        }
 
-            lock (this)
+        bool IOwnableAllocation.TryAcquire(out IntPtr ptr, out int offset, out int length)
+        {
+            // TODO: implement refcounted buffers?

Review Comment:
   Will this get addressed in this PR? If not, we should open an issue for it.



##########
csharp/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs:
##########
@@ -166,6 +169,79 @@ private static dynamic GetPythonSchema()
             }
         }
 
+        private IArrowArray GetTestArray()

Review Comment:
   Can we add some tests using the TestData that has all types?



##########
csharp/src/Apache.Arrow/C/CArrowArrayExporter.cs:
##########
@@ -0,0 +1,210 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+using System;
+using System.Runtime.InteropServices;
+using Apache.Arrow.Memory;
+
+namespace Apache.Arrow.C
+{
+    public static class CArrowArrayExporter
+    {
+        private unsafe delegate void ReleaseArrowArray(CArrowArray* cArray);
+
+        /// <summary>
+        /// Export an <see cref="IArrowArray"/> to a <see cref="CArrowArray"/>. Whether or not the
+        /// export succeeds, the original array becomes invalid. Clone an array to continue using it
+        /// after a copy has been exported.
+        /// </summary>
+        /// <param name="array">The array to export</param>
+        /// <param name="cArray">An allocated but uninitialized CArrowArray pointer.</param>
+        /// <example>
+        /// <code>
+        /// CArrowArray* exportPtr = CArrowArray.Create();
+        /// CArrowArrayExporter.ExportArray(array, exportPtr);
+        /// foreign_import_function(exportPtr);
+        /// </code>
+        /// </example>
+        public static unsafe void ExportArray(IArrowArray array, CArrowArray* cArray)
+        {
+            if (array == null)
+            {
+                throw new ArgumentNullException(nameof(array));
+            }
+            if (cArray == null)
+            {
+                throw new ArgumentNullException(nameof(cArray));
+            }
+            if (cArray->release != null)
+            {
+                throw new ArgumentException("Cannot export array to a struct that is already initialized.", nameof(cArray));
+            }
+
+            ExportedAllocationOwner allocationOwner = new ExportedAllocationOwner();
+            try
+            {
+                ConvertArray(allocationOwner, array.Data, cArray);
+                cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);
+                cArray->private_data = FromDisposable(allocationOwner);
+                allocationOwner = null;
+            }
+            finally
+            {
+                allocationOwner?.Dispose();
+            }
+        }
+
+        /// <summary>
+        /// Export a <see cref="RecordBatch"/> to a <see cref="CArrowArray"/>. Whether or not the
+        /// export succeeds, the original record batch becomes invalid. Clone the batch to continue using it
+        /// after a copy has been exported.
+        /// </summary>
+        /// <param name="batch">The record batch to export</param>
+        /// <param name="cArray">An allocated but uninitialized CArrowArray pointer.</param>
+        /// <example>
+        /// <code>
+        /// CArrowArray* exportPtr = CArrowArray.Create();
+        /// CArrowArrayExporter.ExportRecordBatch(batch, exportPtr);
+        /// foreign_import_function(exportPtr);
+        /// </code>
+        /// </example>
+        public static unsafe void ExportRecordBatch(RecordBatch batch, CArrowArray* cArray)
+        {
+            if (batch == null)
+            {
+                throw new ArgumentNullException(nameof(batch));
+            }
+            if (cArray == null)
+            {
+                throw new ArgumentNullException(nameof(cArray));
+            }
+            if (cArray->release != null)
+            {
+                throw new ArgumentException("Cannot export array to a struct that is already initialized.", nameof(cArray));
+            }
+
+            ExportedAllocationOwner allocationOwner = new ExportedAllocationOwner();
+            try
+            {
+                ConvertRecordBatch(allocationOwner, batch, cArray);
+                cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);
+                cArray->private_data = FromDisposable(allocationOwner);
+                allocationOwner = null;
+            }
+            finally
+            {
+                allocationOwner?.Dispose();
+            }
+        }
+
+        private unsafe static void ConvertArray(ExportedAllocationOwner sharedOwner, ArrayData array, CArrowArray* cArray)
+        {
+            cArray->length = array.Length;
+            cArray->offset = array.Offset;
+            cArray->null_count = array.NullCount;
+            cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);
+            cArray->private_data = null;
+
+            cArray->n_buffers = array.Buffers?.Length ?? 0;
+            cArray->buffers = null;
+            if (cArray->n_buffers > 0)
+            {
+                cArray->buffers = (byte**)Marshal.AllocCoTaskMem(array.Buffers.Length * IntPtr.Size);
+                for (int i = 0; i < array.Buffers.Length; i++)
+                {
+                    ArrowBuffer buffer = array.Buffers[i];
+                    IntPtr ptr;
+                    if (!buffer.TryExport(sharedOwner, out ptr))
+                    {
+                        throw new NotSupportedException(); // TODO

Review Comment:
   Can we address this TODO in this PR?



##########
csharp/src/Apache.Arrow/C/CArrowArrayExporter.cs:
##########
@@ -0,0 +1,210 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+using System;
+using System.Runtime.InteropServices;
+using Apache.Arrow.Memory;
+
+namespace Apache.Arrow.C
+{
+    public static class CArrowArrayExporter
+    {
+        private unsafe delegate void ReleaseArrowArray(CArrowArray* cArray);
+
+        /// <summary>
+        /// Export an <see cref="IArrowArray"/> to a <see cref="CArrowArray"/>. Whether or not the
+        /// export succeeds, the original array becomes invalid. Clone an array to continue using it
+        /// after a copy has been exported.
+        /// </summary>
+        /// <param name="array">The array to export</param>
+        /// <param name="cArray">An allocated but uninitialized CArrowArray pointer.</param>
+        /// <example>
+        /// <code>
+        /// CArrowArray* exportPtr = CArrowArray.Create();
+        /// CArrowArrayExporter.ExportArray(array, exportPtr);
+        /// foreign_import_function(exportPtr);
+        /// </code>
+        /// </example>
+        public static unsafe void ExportArray(IArrowArray array, CArrowArray* cArray)
+        {
+            if (array == null)
+            {
+                throw new ArgumentNullException(nameof(array));
+            }
+            if (cArray == null)
+            {
+                throw new ArgumentNullException(nameof(cArray));
+            }
+            if (cArray->release != null)
+            {
+                throw new ArgumentException("Cannot export array to a struct that is already initialized.", nameof(cArray));
+            }
+
+            ExportedAllocationOwner allocationOwner = new ExportedAllocationOwner();
+            try
+            {
+                ConvertArray(allocationOwner, array.Data, cArray);
+                cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);
+                cArray->private_data = FromDisposable(allocationOwner);
+                allocationOwner = null;
+            }
+            finally
+            {
+                allocationOwner?.Dispose();
+            }
+        }
+
+        /// <summary>
+        /// Export a <see cref="RecordBatch"/> to a <see cref="CArrowArray"/>. Whether or not the
+        /// export succeeds, the original record batch becomes invalid. Clone the batch to continue using it
+        /// after a copy has been exported.
+        /// </summary>
+        /// <param name="batch">The record batch to export</param>
+        /// <param name="cArray">An allocated but uninitialized CArrowArray pointer.</param>
+        /// <example>
+        /// <code>
+        /// CArrowArray* exportPtr = CArrowArray.Create();
+        /// CArrowArrayExporter.ExportRecordBatch(batch, exportPtr);
+        /// foreign_import_function(exportPtr);
+        /// </code>
+        /// </example>
+        public static unsafe void ExportRecordBatch(RecordBatch batch, CArrowArray* cArray)
+        {
+            if (batch == null)
+            {
+                throw new ArgumentNullException(nameof(batch));
+            }
+            if (cArray == null)
+            {
+                throw new ArgumentNullException(nameof(cArray));
+            }
+            if (cArray->release != null)
+            {
+                throw new ArgumentException("Cannot export array to a struct that is already initialized.", nameof(cArray));
+            }
+
+            ExportedAllocationOwner allocationOwner = new ExportedAllocationOwner();
+            try
+            {
+                ConvertRecordBatch(allocationOwner, batch, cArray);
+                cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);
+                cArray->private_data = FromDisposable(allocationOwner);
+                allocationOwner = null;
+            }
+            finally
+            {
+                allocationOwner?.Dispose();
+            }
+        }
+
+        private unsafe static void ConvertArray(ExportedAllocationOwner sharedOwner, ArrayData array, CArrowArray* cArray)
+        {
+            cArray->length = array.Length;
+            cArray->offset = array.Offset;
+            cArray->null_count = array.NullCount;
+            cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);
+            cArray->private_data = null;
+
+            cArray->n_buffers = array.Buffers?.Length ?? 0;
+            cArray->buffers = null;
+            if (cArray->n_buffers > 0)
+            {
+                cArray->buffers = (byte**)Marshal.AllocCoTaskMem(array.Buffers.Length * IntPtr.Size);
+                for (int i = 0; i < array.Buffers.Length; i++)
+                {
+                    ArrowBuffer buffer = array.Buffers[i];
+                    IntPtr ptr;
+                    if (!buffer.TryExport(sharedOwner, out ptr))
+                    {
+                        throw new NotSupportedException(); // TODO
+                    }
+                    cArray->buffers[i] = (byte*)ptr;
+                }
+            }
+
+            cArray->n_children = array.Children?.Length ?? 0;
+            cArray->children = null;
+            if (cArray->n_children > 0)
+            {
+                cArray->children = (CArrowArray**)Marshal.AllocCoTaskMem(IntPtr.Size * array.Children.Length);
+                for (int i = 0; i < array.Children.Length; i++)
+                {
+                    cArray->children[i] = CArrowArray.Create();
+                    ConvertArray(sharedOwner, array.Children[i], cArray->children[i]);
+                }
+            }
+
+            cArray->dictionary = null;
+            if (array.Dictionary != null)
+            {
+                cArray->dictionary = CArrowArray.Create();
+                ConvertArray(sharedOwner, array.Dictionary, cArray->dictionary);
+            }
+        }
+
+        private unsafe static void ConvertRecordBatch(ExportedAllocationOwner sharedOwner, RecordBatch batch, CArrowArray* cArray)
+        {
+            cArray->length = batch.Length;
+            cArray->offset = 0;
+            cArray->null_count = 0;
+            cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);
+            cArray->private_data = null;
+
+            cArray->n_buffers = 1;
+            cArray->buffers = (byte**)Marshal.AllocCoTaskMem(IntPtr.Size);

Review Comment:
   Why are we using `AllocCoTaskMem` here and in other places?



##########
csharp/src/Apache.Arrow/Memory/NativeMemoryManager.cs:
##########
@@ -15,24 +15,32 @@
 
 using System;
 using System.Buffers;
-using System.Diagnostics;
 using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
 using System.Threading;
 
 namespace Apache.Arrow.Memory
 {
-    public class NativeMemoryManager: MemoryManager<byte>
+    public class NativeMemoryManager : MemoryManager<byte>, IOwnableAllocation
     {
         private IntPtr _ptr;
         private readonly int _offset;
         private readonly int _length;
+        private readonly INativeAllocationOwner _owner;
 
         public NativeMemoryManager(IntPtr ptr, int offset, int length)
         {
             _ptr = ptr;
             _offset = offset;
             _length = length;
+            _owner = NativeMemoryAllocator.ExclusiveOwner;
+        }

Review Comment:
   ```suggestion
           public NativeMemoryManager(IntPtr ptr, int offset, int length)
               : this(NativeMemoryAllocator.ExclusiveOwner, ptr, offset, length)
           {
           }
   ```



##########
csharp/src/Apache.Arrow/C/CArrowArrayExporter.cs:
##########
@@ -0,0 +1,210 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+using System;
+using System.Runtime.InteropServices;
+using Apache.Arrow.Memory;
+
+namespace Apache.Arrow.C
+{
+    public static class CArrowArrayExporter
+    {
+        private unsafe delegate void ReleaseArrowArray(CArrowArray* cArray);
+
+        /// <summary>
+        /// Export an <see cref="IArrowArray"/> to a <see cref="CArrowArray"/>. Whether or not the
+        /// export succeeds, the original array becomes invalid. Clone an array to continue using it
+        /// after a copy has been exported.
+        /// </summary>
+        /// <param name="array">The array to export</param>
+        /// <param name="cArray">An allocated but uninitialized CArrowArray pointer.</param>
+        /// <example>
+        /// <code>
+        /// CArrowArray* exportPtr = CArrowArray.Create();
+        /// CArrowArrayExporter.ExportArray(array, exportPtr);
+        /// foreign_import_function(exportPtr);
+        /// </code>
+        /// </example>
+        public static unsafe void ExportArray(IArrowArray array, CArrowArray* cArray)
+        {
+            if (array == null)
+            {
+                throw new ArgumentNullException(nameof(array));
+            }
+            if (cArray == null)
+            {
+                throw new ArgumentNullException(nameof(cArray));
+            }
+            if (cArray->release != null)
+            {
+                throw new ArgumentException("Cannot export array to a struct that is already initialized.", nameof(cArray));
+            }
+
+            ExportedAllocationOwner allocationOwner = new ExportedAllocationOwner();
+            try
+            {
+                ConvertArray(allocationOwner, array.Data, cArray);
+                cArray->release = (delegate* unmanaged[Stdcall]<CArrowArray*, void>)Marshal.GetFunctionPointerForDelegate<ReleaseArrowArray>(ReleaseArray);

Review Comment:
   This applies for all the function pointers we need to set on these structs.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org