简体   繁体   中英

How to unload C++ DLL in C#

I load a C++ DLL using DLLImport in my C# ASP.Net web application. The DLL basically reads some CSV files, and manipulates them and creates new files.

After I ran the method successfully, and run it again then I get C++ exception back.

I want to unload the C++ DLL from the website so a user can re- load the DLL and re run the method. Do you know how to either eliminate this error or get rid of this error message so the DLL can be unloaded after its run?

As far as I'm aware, there's no way to do late binding with C#.

You can do it by creating a C++ DLL and using that, however. Assuming you know enough about C++ to do this, you would just need a single function exported by the DLL, which uses LoadLibrary to load your CSV manipulation DLL, GetProcAddress to retrieve the address of the function you want to call, and then FreeLibrary to release the library.

An example would be something like:

extern "C" {
  __declspec(dllexport) bool InvokeMyFunction() {
    HMODULE lib = LoadLibrary("csvlib.dll");
    if (!lib)
      return false;

    void (*func)(int) = (void (*)(int))GetProcAddress(lib, "MyCsvFunc");
    if (!func)
      return false;

    func(5);

    FreeLibrary(lib);

    return true;
  }
}

This isn't completely safe, though. If possible, it's better to find out what the problem with your DLL function being called more than once is, and fixing it.

If it's your code... why not just provide a FreeResources function?

As an alternative, fixing your code to make your function re-entrant would also work.

According to my information, the unmanaged DLL is always loaded into the main app domain. If it weren't, you would be able to unload the DLL in that way.

Since this is problematic at best, I'd like to propose a different solution: Why not write a separate command line program which does the work and run that as needed. It would run in it's own process and be completely unloaded after running.

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