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/06/01 21:00:56 UTC

[GitHub] [arrow-adbc] eerhardt commented on a diff in pull request #697: feat(csharp): adding C# functionality

eerhardt commented on code in PR #697:
URL: https://github.com/apache/arrow-adbc/pull/697#discussion_r1213675613


##########
csharp/src/Apache.Arrow.Adbc/Interop/LoadDriver.cs:
##########
@@ -0,0 +1,508 @@
+/*
+ * 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.Buffers;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Xml.Linq;
+using Apache.Arrow.Adbc.Core;
+using Apache.Arrow.C;
+using Apache.Arrow.Ipc;
+using Apache.Arrow.Types;
+using Microsoft.Win32.SafeHandles;
+
+#if NETSTANDARD
+using Apache.Arrow.Adbc.Extensions;
+#endif
+
+namespace Apache.Arrow.Adbc.Interop
+{
+    public delegate byte AdbcDriverInit(int version, ref NativeAdbcDriver driver, ref NativeAdbcError error);
+
+    /// <summary>
+    /// Class for working with loading drivers from files
+    /// </summary>
+    public static class LoadDriver
+    {
+        private const string driverInit = "AdbcDriverInit";
+
+        class NativeDriver
+        {
+            public SafeHandle driverHandle;
+            public NativeAdbcDriver driver;
+        }
+
+        /// <summary>
+        /// Class used for Mac interoperability
+        /// </summary>
+        static class MacInterop
+        {
+            const string libdl = "libdl.dylib";
+
+            [DllImport(libdl)]
+            static extern SafeLibraryHandle dlopen(string fileName, int flags);
+
+            [DllImport(libdl)]
+            static extern IntPtr dlsym(SafeHandle libraryHandle, string symbol);
+
+            [DllImport(libdl)]
+            static extern int dlclose(IntPtr handle);
+
+            sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
+            {
+                SafeLibraryHandle() : base(true) { }
+
+                protected override bool ReleaseHandle()
+                {
+                    return dlclose(handle) == 0;
+                }
+            }
+
+            public static NativeDriver GetDriver(string file)
+            {
+                SafeHandle library = dlopen(file, 2); // TODO: find a symbol for 2
+                IntPtr symbol = dlsym(library, "AdbcDriverInit");
+                AdbcDriverInit init = Marshal.GetDelegateForFunctionPointer<AdbcDriverInit>(symbol);
+                NativeAdbcDriver driver = new NativeAdbcDriver();
+                NativeAdbcError error = new NativeAdbcError();
+                byte result = init(1000000, ref driver, ref error);
+                return new NativeDriver { driverHandle = library, driver = driver };
+            }
+        }
+
+        /// <summary>
+        /// Class used for Windows interoperability
+        /// </summary>
+        static class WindowsInterop
+        {
+            const string kernel32 = "kernel32.dll";
+
+            [DllImport(kernel32)]
+            [return: MarshalAs(UnmanagedType.Bool)]
+            static extern bool FreeLibrary(IntPtr libraryHandle);
+
+            [DllImport(kernel32, CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
+            static extern IntPtr GetProcAddress(SafeHandle libraryHandle, string functionName);
+
+            [DllImport(kernel32, CharSet = CharSet.Unicode, SetLastError = true)]
+            static extern SafeLibraryHandle LoadLibraryEx(string fileName, IntPtr hFile, uint flags);
+
+            sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
+            {
+                SafeLibraryHandle() : base(true) { }
+
+                protected override bool ReleaseHandle()
+                {
+                    return FreeLibrary(handle);
+                }
+            }
+
+            public static NativeDriver GetDriver(string file)
+            {
+                SafeHandle library = LoadLibraryEx(file, IntPtr.Zero, 0x1100);
+                IntPtr symbol = GetProcAddress(library, "AdbcDriverInit");
+                AdbcDriverInit init = Marshal.GetDelegateForFunctionPointer<AdbcDriverInit>(symbol);
+                NativeAdbcDriver driver = new NativeAdbcDriver();
+                NativeAdbcError error = new NativeAdbcError();
+                byte result = init(1000000, ref driver, ref error);
+                return new NativeDriver { /* driverHandle = library, */ driver = driver };
+            }
+        }
+
+        /// <summary>
+        /// Loads an <see cref="AdbcDriver"/> from the file system.
+        /// </summary>
+        /// <param name="file">The path to the file</param>
+        /// <returns></returns>
+        public static AdbcDriver Load(string file)
+        {
+            if (file[0] == '/')
+            {
+                return new AdbcDriverNative(MacInterop.GetDriver(file).driver);
+            }
+            else
+            {
+                return new AdbcDriverNative(WindowsInterop.GetDriver(file).driver);
+            }
+        }
+
+        /// <summary>
+        /// Native implementation of <see cref="AdbcDriver"/>
+        /// </summary>
+        sealed class AdbcDriverNative : AdbcDriver
+        {
+            private NativeAdbcDriver _nativeDriver;
+
+            public AdbcDriverNative(NativeAdbcDriver nativeDriver)
+            {
+                _nativeDriver = nativeDriver;
+            }
+
+            /// <summary>
+            /// Opens a database
+            /// </summary>
+            /// <param name="parameters"></param>
+            /// <returns></returns>
+            public unsafe override AdbcDatabase Open(Dictionary<string, string> parameters)
+            {
+                NativeAdbcDatabase nativeDatabase = new NativeAdbcDatabase();
+                using (ErrorHelper error = new ErrorHelper())
+                {
+                    error.Call(
+                        Marshal.GetDelegateForFunctionPointer<DatabaseFn>((IntPtr)_nativeDriver.DatabaseNew),
+                        ref nativeDatabase);
+
+                    DatabaseSetOption setOption = Marshal.GetDelegateForFunctionPointer<DatabaseSetOption>((IntPtr)_nativeDriver.DatabaseSetOption);
+                    if (parameters != null)
+                    {
+                        foreach (KeyValuePair<string, string> pair in parameters)
+                        {
+                            error.Call(setOption, ref nativeDatabase, pair.Key, pair.Value);
+                        }
+                    }
+                    error.Call(Marshal.GetDelegateForFunctionPointer<DatabaseFn>((IntPtr)_nativeDriver.DatabaseInit), ref nativeDatabase);
+                }
+
+                return new AdbcDatabaseNative(_nativeDriver, nativeDatabase);
+            }
+
+            public unsafe override void Dispose()
+            {
+                if (_nativeDriver.release != null)
+                {
+                    using (ErrorHelper error = new ErrorHelper())
+                    {
+                        try
+                        {
+                            error.Call(Marshal.GetDelegateForFunctionPointer<DriverRelease>((IntPtr)_nativeDriver.release), ref _nativeDriver);

Review Comment:
   You don't need to / shouldn't use `Marshal.GetDelegateForFunctionPointer` here. Instead you can invoke the function like:
   
   ```C#
   fixed (NativeAdbcDriver* driver = &nativeDriver)
   {
       _nativeDriver.release(driver);
   }
   ```
   
   You'll probably have to rewrite your ErrorHelper for a new pattern. But there's no reason to allocate a managed object (a Delegate) just to call this function - or any native function.



-- 
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