LoadLibrary doesn't work when compiled to AnyCpu

和自甴很熟 提交于 2019-12-08 05:57:57

问题


I am developing a c# application that extract a cab file from a setup package.

to do that I am using LoadLibrary. this is the pinvoke C# signature.

 [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
 internal static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);

The above code works fine when compiling the project to x86, but if I compile it to anycpu it fails, and the last win32 error is:

"%1 is not a valid Win32 application"

I tried to use IntPtr insted of a string, and also to use dfferent charset but nothing worked.


回答1:


LoadLibrary works fine. The problem is that you are attempting to load a 32 bit DLL into a 64 bit process. This cannot be done and the error message that you quote is the result of attempting to mix modules with non-matching bitness.

The problem is not in the p/invoke signature for LoadLibrary, rather the call to LoadLibrary that is not shown in the question. That call is resulting in an attempt to load a 32 bit DLL into your 64 bit process. Unless you have 64 bit versions of all the native DLLs that you load, you'll need to stick to x86.

As an aside there's really no point in using CharSet.Ansi for this function. Since .net use UTF-16 text natively you would be far better off using CharSet.Unicode, avoiding any character set conversions and making sure that your program can support Unicode file names.

Update

In the comments you ask if it is possible to load a 32 bit DLL from a 64 bit process for the purpose of extracting resources. It is possible, but not with LoadLibrary. You need to call LoadLibraryEx passing LOAD_LIBRARY_AS_DATAFILE.



来源:https://stackoverflow.com/questions/17146185/loadlibrary-doesnt-work-when-compiled-to-anycpu

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