How to use the correct unmanaged DLL file according CPU architecture? (32 / 64 bits)

元气小坏坏 提交于 2019-12-29 06:23:14

问题


I have to use a C++ DLL file from an ASP.NET site. The site will be hosted on both 32 and 64 bits environments.

I have a 32 and 64 bits version of the unmanaged DLL file. How do I import the methods from the correct one according the current server architecture?

Like someone posted, this could be handled as a deployment problem. My concern is: the web application consuming this DLL file is huge, and we don't have a deployment document. No one will remember to deploy the correct DLL file, so I'm trying to remove the human factor from the solution :)


回答1:


Simplest approach would be to give the two native libraries the same filename in two different directories, then adjust your application DLL search path depending on the bitness.

http://www.pinvoke.net/default.aspx/kernel32.setdlldirectory




回答2:


To get the compiler/framework to do most of the work you need to

  1. have multiple build 'platforms' (typically x86, x64 - remove AnyCPU)
  2. set each "platform target" configuration for each build config
  3. we added conditional compilation symbols __WIN32 & __X64

List the different implementations for your functions according to platform, including different dll names if you need to have both installed at once.

#if __WIN32
        public delegate int Move(int target);
        [DllImport("my.dll", SetLastError = true, CharSet = CharSet.Auto)]
#elif __X64
        public delegate int Move(int target);
        [DllImport("my64.dll", SetLastError = true, CharSet = CharSet.Auto)]
#endif

Otherwise you can use loadlib and manage the marshalling yourself.




回答3:


As we know that we cannot add unmanaged DLL files using add reference. So we need an alternative way to handle unmanaged DLLS files according to CPU architecture that is add DLL files in your project directories.

  1. Create new folders into your project named x32 and x64.
  2. Copy your DLL files into these folders according to architecture.
  3. Select the files and open properties, Change "Copy to output directory: Copy always"
  4. Repeat this on all files in both folders

Now build your project in any platform when you will build the project both x86 and x64 folder will be copyed in bin folder. When this will run on server it will use unmanaged DLL files according to CPU architecture.



来源:https://stackoverflow.com/questions/3638751/how-to-use-the-correct-unmanaged-dll-file-according-cpu-architecture-32-64-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!