Allow PDFium to support x86 and x64

1

I've built a WinForms app which uses PDFium to print PDF documents. I installed PDFium from NuGet, and it created two subfolders in my project - x86 and x64 - as expected, each with the relevant version of pdfium.dll inside. My application's target platform is set to Any CPU.

When I run the application in debug on my Windows 10 64-bit machine it works perfectly. However, when I release the application and install it for real on the same computer, PDFium throws an exception:

System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

After doing some research, I changed my application's target platform to x86 and removed the x64 subfolder from my project. The application now works perfectly after release, so the problem is solved.

However, I'd like to know if there's a way that I can get my application to work so that it supports both x86 and x64, using the appropriate version of PDFium for the target computer. It'd be nice if it'd install a 64-bit version on machines which can support it (which is most of them within our organisation, but I feel that I need to go with 32-bit if I have to choose one or the other, to ensure compatibility).

c#
winforms
pdfium

2 Answers

4

I have used this approach. The main idea is to determine if the program is running on 32 or 64bit environments. This is done by checking the size of the pointer. Depending on the result of this check the library pdfium.dll is dynamically loaded from the x86 or the x64 subdirectory of the application path.

private static bool TryLoadNativeLibrary(string path)
{
    if (path == null)
        return false;

    path = Path.Combine(path, IntPtr.Size == 4 ? "x86" : "x64");

    path = Path.Combine(path, "pdfium.dll");

    return File.Exists(path) && LoadLibrary(path) != IntPtr.Zero;
}

[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName);
answered on Stack Overflow Mar 27, 2017 by Ralf Bönning
0

This turned out not to be anything to do with PDFium. In my script used during installation of the released application, the two versions of pdfium.dll were both set to publish to the application's root folder, rather than subfolders named x32 and x64. As a result, during installation the x32 version of the dll was overwriting the x64 version, resulting in the application not having the x64 dll at all.

answered on Stack Overflow Mar 27, 2017 by Philip Stratford

User contributions licensed under CC BY-SA 3.0