我希望有人能帮我将C++ dll加载到C#项目中并重新加载。
我使用文件选择器将C++ dll加载到项目中,然后将其复制到名为Process.dll的文件。然后我使用这个dll来完成它的任务,稍后我需要能够加载一个新的dll并让它完成它的任务。
步骤如下:
- 用户选择一个dll
- dll被复制到Processor.dll
- 创建我的处理器类,该类使用dll导入使用dll
- 使用dll并调用其各种函数等
- 回到第1步。
我有两个类
- ProcessTab - C# 类,其中包含GUI并调用ProcessPlugin中的类
- ProcessPlugin - C# 类,调用C++类,它使用dllImport等
代码如下:
class ProcessorTab
{
private void buttonLoadProcDll_Click(object sender, RoutedEventArgs e)
{
// Open dll and copy it to "\\Processor.dll"
processorPlugIn = new ProcessorPlugIn(this);
return;
}
private void DestroyProcessor_Click(object sender, RoutedEventArgs e)
{
processorPlugIn.UnloadModule("Processor.dll");
processorPlugIn = null;
}
}
class ProcessorPlugIn
{
public const string PluginName = "Processor.dll";
public LibraryInfo info;
ErrorCode err;
private IntPtr pRxClass;
private IntPtr pTxClass;
[DllImport("kernel32", SetLastError = true)]
static extern bool FreeLibrary(IntPtr hModule);
[System.Runtime.InteropServices.DllImportAttribute(PluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern ErrorCode VE_ProcessorPluginLib_Rx_API_Constructor(ref IntPtr pRx);
[System.Runtime.InteropServices.DllImportAttribute(PluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern ErrorCode VE_ProcessorPluginLib_Rx_API_Destructor(ref IntPtr pRx);
[System.Runtime.InteropServices.DllImportAttribute(PluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern ErrorCode VE_ProcessorPluginLib_Tx_API_Constructor(ref IntPtr pTx);
[System.Runtime.InteropServices.DllImportAttribute(PluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern ErrorCode VE_ProcessorPluginLib_Tx_API_Destructor(ref IntPtr pTx);
public ProcessorPlugIn(MainWindow mWindow)
{
pRxClass = new IntPtr();
pTxClass = new IntPtr();
if (VE_ProcessorPluginLib_Rx_API_Constructor(ref pRxClass) != ErrorCode.EC_OK) // ERROR HERE: AccessViolationException was unhandled
MessageBox.Show("Error constructing Rx");
if (VE_ProcessorPluginLib_Tx_API_Constructor(ref pTxClass) != ErrorCode.EC_OK)
MessageBox.Show("Error constructing Tx");
}
public void UnloadModule(string moduleName)
{
if (VE_ProcessorPluginLib_Rx_API_Destructor(ref pRxClass) != ErrorCode.EC_OK)
MessageBox.Show("Error destropying Rx");
if (VE_ProcessorPluginLib_Tx_API_Destructor(ref pTxClass) != ErrorCode.EC_OK)
MessageBox.Show("Error destropying Rx");
foreach (ProcessModule mod in Process.GetCurrentProcess().Modules)
{
if (mod.ModuleName == moduleName)
{
FreeLibrary(mod.BaseAddress);
}
}
}
}
一切都很正常,我调用了C ++ dll中的方法并获得了预期的输出等等。但是当我尝试摧毁它并重新加载它时,我遇到了一个错误——AccessViolationException未处理,如代码中的注释所示。
有谁知道我该如何解决这个问题吗?
提前感谢您的帮助。
LoadLibrary
后,才能调用FreeLibrary
。 - David Heffernan