I want to dynamically load a dll and construct a MyDllClass object. My code is roughly as follows(unrelevant parts stripped):
MyDllClass.cs
namespace MyDllNameSpace
{
public class MyDllClass
{
private EventCallBack m_DelegateCallBack = null;
public MyDllClass(EventCallBack eventCallBack)
{
m_DelegateCallBack = eventCallBack;
}
public MyDllClass()
{
}
...
}
}
MyDllCallBackNameSpace.cs
namespace MyDllCallBackNameSpace
{
public delegate void EventCallBack(string message);
}
I managed to construct the object using the empty constructor but I couldn’t get other constructor working. I get ArgumentException
at System.Reflection.RuntimeConstructorInfo.InternalInvoke()
at System.Reflection.RuntimeConstructorInfo.Invoke()
at System.Reflection.ConstructorInfo.Invoke() at MyProgram.InitMyObject()
at ...
Here is my code:
MyProgram.cs
public void InitMyObject(EventCallBack callBack)
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(DLL_PATH);
Type type = assembly.GetType(CLASS_NAME);
ConstructorInfo[] constructors = type.GetConstructors();
if (type != null)
{
// empty constructor, works!!!
//return constructors[1].Invoke(new object[0]);
// This one gives InvalidArgument exception
return constructors[0].Invoke(new object[] {callBack});
}
return null;
}
MyDllCallBackNameSpace.cs file has been added to both projects(the .dll & the .exe project) and references the same physical file on my drive. But I suspect that it is still treated as different. Any ideas why it is not working, or any workarounds?
I managed to fix this buy moving
MyDllCallBackNameSpace.csinto another dll. Then I referenced that dll from both projects.