开发者

Can a C# AnyCPU project include a platform specific dll

开发者 https://www.devze.com 2023-02-05 02:42 出处:网络
Our product is based on a bunch of C++ projects but we are now using C# projects for the front end.We are also now doing a 64 bit version.

Our product is based on a bunch of C++ projects but we are now using C# projects for the front end. We are also now doing a 64 bit version.

Our plan is to build all of t开发者_运维百科he C# dlls as AnyCPU. The C# projects will have references to the C++ dlls in a common bin folder. When building x64 the bin folder will contain x64 versions of our c++ dlls and when building Win32 the bin folder will contain 32 bit versions of our C++ dlls. So the C# projects will be building AnyCPU but including either an x64 or Win32 c++ dll.

My question is, will this work? At runtime everything should be either all 32 or all 64 depending on which exe we are running, but can compile time handle a project targeting AnyCPU that includes a platform specific dll? Or will we have to make platform specific versions of all our C# dlls? Thanks


This is primarily a deployment problem, getting the right DLLs selected for the right operating system. Pretty straight-forward if you create two setup projects, one for x86 and another for x64.

Making it work transparently is possible too. You'd create, say, an x86 and an x64 sub-directory in the directory that contains your EXE and put respectively the 32-bit and the 64-bit builds of the DLLs in those sub-directories. At startup, check IntPtr.Size to know the bit-ness of your process. Then pinvoke SetDllDirectory accordingly so that Windows will find the correct DLL. Like this:

using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
...
        public static void SetupDllDirectory() {
            string path = Assembly.GetEntryAssembly().Location;
            path = Path.Combine(path, IntPtr.Size == 8 ? "x64" : "x86");
            bool ok = SetDllDirectory(path);
            if (!ok) throw new System.ComponentModel.Win32Exception();
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetDllDirectory(string path);

Use a post build event to copy the DLLs. Using Environment.SetEnvironmentVariable() to append the directory to the PATH environment variable is yet another approach.


As far as I remember, this works.

I had only 32bit DLLs, c# compiled and it crashed on startup. So if you put there 64bit DLLs, I think you don't need to recompile C#.


I've done it. Although it gives compile warnings.


It should work, I have used such approach in the past and it works fine. what kind of compile warnings do you get?

0

精彩评论

暂无评论...
验证码 换一张
取 消