Introduction
Today someone was asking how he can load a DLL dynamically with .NET. For
some design related reasons he didn't want to add a reference to the DLL at
compile time. For all I know this might be something everyone knew about except
this particular individual and me. But I didn't know anything about this and I
had never thought that anyone would want to do anything like that. Anyway as I
found out it was really easy. This example is completely in MC++. Just in case
someone starts flaming me saying this is an oft-discussed topic, I can always
claim this is the first MC++ example. And my google searches kept directing me
to pages that talked about normal dynamic loading of DLLs [means the non-.NET
stuff]
The DLL
Create a simple class library called Abc.dll. This will be the DLL which we
will load dynamically.
#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
namespace Abc
{
public __gc class Class1
{
public:
String* Hello(String* str)
{
return String::Concat(S"Hello ",str);
}
};
}
The Program
Okay, this is the little program that will load the above DLL, and call the
Hello function, passing a string to it and also getting back the string that the
function returns. Remember that Abc.dll must be in the same directory as our
program's executable. I believe there are ways to put the DLL in some special
directories that all .NET programs look into, but I am totally ignorant of such
things.
#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
using namespace System::Reflection;
int wmain(void)
{
Assembly *a = Assembly::Load("Abc");
Type *t = a->GetType("Abc.Class1");
MethodInfo *mi = t->GetMethod("Hello");
Console::WriteLine("Return type of *{0}* method is *{1}*",
mi->Name,mi->ReturnType);
Object *o = Activator::CreateInstance(t);
String *args[] = new String*[1];
args[0]= S"Nish";
String *s1=static_cast<String*>(mi->Invoke(o,args));
Console::WriteLine(s1);
return 0;
}
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award (14 consecutive awards as of between 2002-2016).
Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.
Nish's Technology Blog :
voidnish.wordpress.com