Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Automatic load x32/x64 asseblies  (Read 2247 times)

0 Members and 1 Guest are viewing this topic.

mkalex777

  • Full Member
  • ***
  • Posts: 206
    • View Profile
Automatic load x32/x64 asseblies
« on: September 23, 2015, 04:13:46 am »
Hi guys,

I'm looking for a good way to load SFML.NET libraries automatically depends on current process architecture.

Currently I implemented a small trick which allows to use Any CPU target for the main project, and it will run on both 32 and 64 bit system with correct loading of SFML.NET assemblies.

Here is the sample:
    class Program
    {
        static Program()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AppDomain_OnAssemblyResolve;
        }

        static void Main(string[] args)
        {
            Logger.Info("System:  {0}", Environment.Is64BitOperatingSystem ? "x64" : "x32");
            Logger.Info("Process: {0}", Environment.Is64BitProcess ? "x64" : "x32");
            using (var myApp = new MyApp())
            {
                myApp.Run();
            }
        }

        private static readonly string[] SfmlAsms = new[]
        {
            "sfmlnet-audio-2",
            "sfmlnet-graphics-2",
            "sfmlnet-system-2",
            "sfmlnet-window-2",
        };

        private static Assembly AppDomain_OnAssemblyResolve(object sender, ResolveEventArgs e)
        {
            if (e.Name == null ||
                !SfmlAsms.Any(arg => e.Name.StartsWith(arg, StringComparison.InvariantCultureIgnoreCase)))
            {
                return null;
            }
            var name = e.Name;
            var commaIndex = name.IndexOf(',');
            if (commaIndex >= 0)
            {
                name = name.Substring(0, commaIndex);
            }
            var folder = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location);
            folder = Path.Combine(folder, Environment.Is64BitProcess ? "x64" : "x32");
            var fileInfo = new FileInfo(Path.Combine(folder, name+".dll"));
            if (!fileInfo.Exists)
            {
                return null;
            }
            return Assembly.LoadFrom(fileInfo.FullName);
        }
    }
 

With this code you should place all SFML.NET assemblies and libraries into the folders "x32" and "x64" near exe.
The code catch assembly resolving event and set correct path depends on process architecture.
So, there is no need to build several executable for each platforms.

If you have any idea on how to add support for linux/mono, any comments are welcome :)

UPDATED: added minor fix
« Last Edit: September 23, 2015, 05:10:18 am by mkalex777 »

 

anything