简体   繁体   中英

Error loading DLL - Console App - Visual Studio Community 2022

I'm trying to load a third-party DLL in a Console App project created in Visual Studio Community 2022. Environment is Windows 10. I have tried both .NET 5.0 and 6.0

No matter what I have tried, I get the error "Unhandled exception. System.BadImageFormatException: Bad IL format. The format of the file is invalid."

I have checked and normally this error is because I'm trying to load a x64 DLL in a x86 app or viceversa, but I know this is not the case because:

  • I have been able to load this specific DLL in C (using LoadLibrary() in Codeblocks) and JAVA (using JNA), configuring the applications for a x86 target platform. I have configured this console app for a x86 target platform as well in properties.
  • The DLL when loaded starts writing to a log file. The log file destination is fixed, and can't be deactivated. Whenever I run my app, I see the log being written to. I realized that the log was being written to by using Sysinternals' Process Monitor.

The log only says

INFO: 2.23.00 12:14:27(00000015) PCLService.cpp:138 [22.11.2021] logCreate

INFO: 2.23.00 12:14:27(00000000) PCLService.cpp:141 PDA_Manager: DllMain attached

INFO: 2.23.00 12:14:27(00000000) PCLService.cpp:145 PDA_Manager: DllMain detach

Normally, the detach should only happen when the DLL is unloaded/program is closed. Here it happens automatically. It is like the program can't keep the DLL loaded, giving the error message.

Here is my current code.

using System;
using System.Reflection;

namespace ConsoleApp5
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //var DLL = Assembly.LoadFile(@"C:\Documentacion\VisaNet\Proyectos\Simpler\bin\Debug\x86\PCLService.dll");
            var DLL = Assembly.LoadFrom("PCLService.dll");
            Console.ReadLine();
        }
    }
}

I have tried both LoadFrom() and LoadFile(). Even tried Load(), but the error is different about additional information that I don't know how to get.

I have checked Assembly Binding Log Viewer (fuslogvw.exe) and Process Monitor. I do not see any obvious problem.

进程监视器屏幕截图

I assume that whatever error happens, it did happen by the time of the last 4 entries about PCLService.log, which must the ones writing in the DLL log about detaching, because there are no more entries about the log in Process Monitor.

While I'm a experienced programmer, I'm totally new to Visual Studio / C#

Any assistance would be welcome.

To call a native dll, you have to use [DllImport] together with a function prototype. Any of the Assembly.LoadXXX() methods are for managed libraries only. Maybe Using a 32bit or 64bit dll in C# DllImport will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM