|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.IO; |
| 6 | +using System.Reflection; |
| 7 | +using System.Runtime.InteropServices; |
| 8 | +using Xunit; |
| 9 | + |
| 10 | +public class DllImportSearchPathsTest |
| 11 | +{ |
| 12 | + private static string Subdirectory => Path.Combine(NativeLibraryToLoad.GetDirectory(), "subdirectory"); |
| 13 | + |
| 14 | + [Fact] |
| 15 | + public static void AssemblyDirectory_NotFound() |
| 16 | + { |
| 17 | + // Library should not be found in the assembly directory |
| 18 | + Assert.Throws<DllNotFoundException>(() => NativeLibraryPInvoke.Sum(1, 2)); |
| 19 | + } |
| 20 | + |
| 21 | + public static bool CanLoadAssemblyInSubdirectory => |
| 22 | + !TestLibrary.Utilities.IsNativeAot && !TestLibrary.PlatformDetection.IsMonoLLVMFULLAOT; |
| 23 | + |
| 24 | + [ConditionalFact(nameof(CanLoadAssemblyInSubdirectory))] |
| 25 | + public static void AssemblyDirectory_Found() |
| 26 | + { |
| 27 | + // Library should be found in the assembly directory |
| 28 | + var assembly = Assembly.LoadFile(Path.Combine(Subdirectory, $"{nameof(DllImportSearchPathsTest)}.dll")); |
| 29 | + var type = assembly.GetType(nameof(NativeLibraryPInvoke)); |
| 30 | + var method = type.GetMethod(nameof(NativeLibraryPInvoke.Sum)); |
| 31 | + |
| 32 | + int sum = (int)method.Invoke(null, new object[] { 1, 2 }); |
| 33 | + Assert.Equal(3, sum); |
| 34 | + } |
| 35 | + |
| 36 | + [Fact] |
| 37 | + [PlatformSpecific(TestPlatforms.Windows)] |
| 38 | + public static void AssemblyDirectory_Fallback_Found() |
| 39 | + { |
| 40 | + string currentDirectory = Environment.CurrentDirectory; |
| 41 | + try |
| 42 | + { |
| 43 | + Environment.CurrentDirectory = Subdirectory; |
| 44 | + |
| 45 | + // Library should not be found in the assembly directory, but should fall back to the default OS search which includes CWD on Windows |
| 46 | + int sum = NativeLibraryPInvoke.Sum(1, 2); |
| 47 | + Assert.Equal(3, sum); |
| 48 | + } |
| 49 | + finally |
| 50 | + { |
| 51 | + Environment.CurrentDirectory = currentDirectory; |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +public class NativeLibraryPInvoke |
| 57 | +{ |
| 58 | + public static int Sum(int a, int b) |
| 59 | + { |
| 60 | + return NativeSum(a, b); |
| 61 | + } |
| 62 | + |
| 63 | + [DllImport(NativeLibraryToLoad.Name)] |
| 64 | + [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory)] |
| 65 | + static extern int NativeSum(int arg1, int arg2); |
| 66 | +} |
0 commit comments