wjones127 commented on code in PR #34133:
URL: https://github.com/apache/arrow/pull/34133#discussion_r1124983227


##########
csharp/src/Apache.Arrow/C/CArrowSchema.cs:
##########
@@ -0,0 +1,599 @@
+// 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.IO;
+using System.Linq;
+using System.Runtime.InteropServices;
+using Apache.Arrow.Types;
+
+[UnmanagedFunctionPointer(CallingConvention.StdCall)]
+public delegate void ReleaseCArrowSchema(IntPtr schema);
+
+namespace Apache.Arrow.C
+{
+    /// <summary>
+    /// An Arrow C Data Interface Schema, which represents a type, field, or 
schema.
+    /// </summary>
+    /// 
+    /// <remarks>
+    /// This is used to export <see cref="ArrowType"/>, <see cref="Field"/>, or
+    /// <see cref="Schema"/> to other languages. It matches the layout of the
+    /// ArrowSchema struct described in 
https://github.com/apache/arrow/blob/main/cpp/src/arrow/c/abi.h.
+    /// </remarks>
+    [StructLayout(LayoutKind.Sequential)]
+    public struct CArrowSchema
+    {
+        public IntPtr format;
+        public IntPtr name;
+        public IntPtr metadata;
+        public long flags;
+        public long n_children;
+        public IntPtr children;
+        public IntPtr dictionary;
+        [MarshalAs(UnmanagedType.FunctionPtr)]
+        public ReleaseCArrowSchema release;
+        public IntPtr private_data;
+
+        private static char FormatTimeUnit(TimeUnit unit) => unit switch
+        {
+            TimeUnit.Second => 's',
+            TimeUnit.Millisecond => 'm',
+            TimeUnit.Microsecond => 'u',
+            TimeUnit.Nanosecond => 'n',
+            _ => throw new InvalidDataException($"Unsupported time unit for 
export: {unit}"),
+        };
+
+        private static string GetFormat(IArrowType datatype)
+        {
+            switch (datatype)
+            {
+                case NullType _: return "n";
+                case BooleanType _: return "b";
+                // Integers
+                case Int8Type _: return "c";
+                case UInt8Type _: return "C";
+                case Int16Type _: return "s";
+                case UInt16Type _: return "S";
+                case Int32Type _: return "i";
+                case UInt32Type _: return "I";
+                case Int64Type _: return "l";
+                case UInt64Type _: return "L";
+                // Floats
+                case HalfFloatType _: return "e";
+                case FloatType _: return "f";
+                case DoubleType _: return "g";
+                // Decimal
+                case Decimal128Type decimalType:
+                    return $"d:{decimalType.Precision},{decimalType.Scale}";
+                case Decimal256Type decimalType:
+                    return 
$"d:{decimalType.Precision},{decimalType.Scale},256";
+                // Binary
+                case BinaryType _: return "z";
+                case StringType _: return "u";
+                case FixedSizeBinaryType binaryType:
+                    return $"w:{binaryType.ByteWidth}";
+                // Date
+                case Date32Type _: return "tdD";
+                case Date64Type _: return "tdm";
+                // Time
+                case Time32Type timeType:
+                    return String.Format("tt{0}", 
FormatTimeUnit(timeType.Unit));
+                case Time64Type timeType:
+                    // Same prefix as Time32, but allowed time units are 
different.
+                    return String.Format("tt{0}", 
FormatTimeUnit(timeType.Unit));
+                // Timestamp
+                case TimestampType timestampType:
+                    return String.Format("ts{0}:{1}", 
FormatTimeUnit(timestampType.Unit), timestampType.Timezone);
+                // Nested
+                case ListType _: return "+l";
+                case StructType _: return "+s";
+                // Dictionary
+                case DictionaryType dictionaryType:
+                    return GetFormat(dictionaryType.IndexType);
+                default: throw new NotImplementedException($"Exporting 
{datatype.Name} not implemented");
+            };
+        }
+
+        private static long GetFlags(IArrowType datatype, bool nullable = true)
+        {
+            long flags = 0;
+
+            if (nullable)
+            {
+                flags |= ArrowFlagNullable;
+            }
+
+            if (datatype is DictionaryType dictionaryType)
+            {
+                if (dictionaryType.Ordered)
+                {
+                    flags |= ArrowFlagDictionaryOrdered;
+                }
+            }
+
+            // TODO: when we implement MapType, make sure to set the 
KEYS_SORTED flag.
+            return flags;
+        }
+
+        /// <summary>
+        /// Whether this field is semantically nullable (regardless of whether 
it actually has null values)
+        /// </summary>
+        public const long ArrowFlagDictionaryOrdered = 1;
+        /// <summary>
+        /// For dictionary-encoded types, whether the ordering of dictionary 
indices is semantically meaningful.
+        /// </summary>
+        public const long ArrowFlagNullable = 2;
+        /// <summary>
+        /// For map types, whether the keys within each map value are sorted.
+        /// </summary>
+        public const long ArrowFlagMapKeysSorted = 4;
+
+        /// <summary>
+        /// Get the value of a particular flag.
+        /// </summary>
+        /// <remarks>
+        /// Known valid flags are <see cref="ArrowFlagDictionaryOrdered" />,
+        /// <see cref="ArrowFlagNullable" />, and <see 
cref="ArrowFlagMapKeysSorted" />.
+        /// </remarks>
+        public bool GetFlag(long flag)
+        {
+            return (flags & flag) == flag;
+        }
+
+        private static IntPtr ConstructChildren(IArrowType datatype, out long 
numChildren)
+        {
+            if (datatype is NestedType nestedType)
+            {
+                IReadOnlyList<Field> fields = nestedType.Fields;
+                int numFields = fields.Count;
+                numChildren = numFields;
+
+                unsafe
+                {
+                    IntPtr* pointerList = 
(IntPtr*)Marshal.AllocHGlobal(numFields * IntPtr.Size);
+
+                    for (var i = 0; i < numChildren; i++)
+                    {
+                        var cSchema = new CArrowSchema(fields[i]);
+                        IntPtr exportedSchema = cSchema.AllocateAsPtr();
+                        pointerList[i] = exportedSchema;
+                    }
+
+                    return (IntPtr)pointerList;
+                }
+
+            }
+            else
+            {
+                numChildren = 0;
+                return IntPtr.Zero;
+            }
+        }
+
+        private IntPtr GetChild(int i)
+        {
+            if (i >= n_children)
+            {
+                throw new Exception("Child index out of bounds.");
+            }
+            if (children == IntPtr.Zero)
+            {
+                throw new Exception("Children array is null.");
+            }
+            unsafe
+            {
+                return ((IntPtr*)children)[i];
+            }
+        }
+
+        private static IntPtr ConstructDictionary(IArrowType datatype)
+        {
+            if (datatype is DictionaryType dictType)
+            {
+                var cSchema = new CArrowSchema(dictType.ValueType);
+                return cSchema.AllocateAsPtr();
+            }
+            else
+            {
+                return IntPtr.Zero;
+            }
+        }
+
+        /// <summary>
+        /// Initialize the exported C schema as an Arrow type.
+        /// </summary>
+        /// <param name="datatype">The Arrow type to export.</param>
+        public CArrowSchema(IArrowType datatype)

Review Comment:
   The intention is both ways: Import C data to C#, and export C# data to C.
   
   This would enable reading / writing Parquet to/from Arrow in ParquetSharp, 
for instance.
   Reading: Parquet -> C++ Arrow -> C data interface -> C# Arrow
   Writing: C# Arrow -> C data interface -> C++ Arrow -> Parquet
   
   We could instead have an `Importer` and `Exporter` class
   
   ```csharp
   public class CDataImporter
   {
       public static ArrowType ImportType(IntPtr ptr);
       public static Field ImportField(IntPtr ptr);
       public static Schema ImportSchema(IntPtr ptr);
   }
   ```
   
   Or simple have methods on various types:
   
   ```csharp
   public class ArrowType
   {
       public IntPtr ExportToC();
   }
   
   public class Field
   {
       public IntPtr ExportToC();
   }
   ```
   
   



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to