Question

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.

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top