I'm trying to unload a C++ DLL from my C# program and then reload it and useits functions. for the unloading part i Used this answer: Unload a DLL loaded using DllImport
In order to reload it I used the LoadLibrary function. This is my code:
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
internal class Program
{
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeLibrary(IntPtr hModule);
[DllImport("TestLibrary.dll", SetLastError = true)]
private static extern int GetValue();
private static void Main(string[] args)
{
int val = GetValue();
IntPtr p2 = LoadLibrary("TestLibrary.dll");
bool isFree = FreeLibrary(p2);
isFree = FreeLibrary(p2);
p2 = LoadLibrary("TestLibrary.dll");
val = GetValue();
}
}
}
The weird thing is that pinvoke still works when I reload the module.
Isn't the module supposed to be loaded to a different part of the memory?
Can I do it the way I did or am I going to have trouble with it?