5,427,303 members and growing! (16,808 online)
Email Password   helpLost your password?
Languages » C++ / CLI » General     Intermediate

Dynamically loading a DLL - MC++

By Nishant Sivakumar

Shows how you can load an assembly at run time, instantiate a class in that assembly and call methods on the class
C++/CLI.NET 1.0, Win2K, WinXP, Windows, .NET, Visual Studio, Dev

Posted: 27 May 2002
Updated: 27 May 2002
Views: 143,253
Bookmarked: 16 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
26 votes for this Article.
Popularity: 4.95 Rating: 3.50 out of 5
1 vote, 7.7%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
3 votes, 23.1%
4
9 votes, 69.2%
5

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:
        //This simply prefixes a Hello

        //to whatever string is passed

        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)
{
    //First we load our assembly

    //using the display name

    Assembly *a = Assembly::Load("Abc");

    //Now we get the type of the object

    //we want to instantiate. Since our class is

    //part of the assembly we have to use the full

    //name of the class with assembly name

    Type *t = a->GetType("Abc.Class1");

    //The MethodInfo class is used to

    //describe a method. It holds metadata about

    //a particular method. We get the MethodInfo for

    //our Hello method    

    MethodInfo *mi = t->GetMethod("Hello");    
    //Just showing off some public properties

    Console::WriteLine("Return type of *{0}* method is *{1}*",
        mi->Name,mi->ReturnType);

    //We create an instance of our object.

    //Here the default constructor is called.

    Object *o = Activator::CreateInstance(t);

    //Prepare our argument list

    String *args[] = new String*[1]; 
    args[0]= S"Nish";  
  
    //We use Invoke to call the Hello method

    //on the object we got from CreateInstance above

    //We pass to it our arguments as an Object array

    String *s1=static_cast<String*>(mi->Invoke(o,args));
    Console::WriteLine(s1);
    return 0;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Nishant Sivakumar


Sitebuilder, Mvp
Nish is a real nice guy living in Atlanta, who has been coding since 1990, when he was 13 years old. Originally from sunny Trivandrum in India, he recently moved to Atlanta from Toronto and is a little sad that he won't be able to play in snow anymore.

Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com

Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.

Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.

Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.
Location: United States United States

Other popular C++ / CLI articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 31 (Total in Forum: 31) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralHow to load mixed managed dllmembersandi_ro6:42 3 Oct '07  
GeneralInterface and casting issuememberY_R5:30 4 Aug '07  
GeneralUsing OpenGL and GNU in Visual C++.NET (2002)memberSctt H. Chang6:21 21 Aug '03  
GeneralRe: Using OpenGL and GNU in Visual C++.NET (2002)memberFfelagund11:30 1 Mar '04  
GeneralHow tomembervinodgs11:31 5 Aug '03  
GeneralRe: How toeditorNishant S15:45 5 Aug '03  
GeneralRe: How tomembervinodgs17:35 5 Aug '03  
GeneralMethodInfo null pointer (help please)memberbrow08337:30 27 Jun '03  
GeneralFound it!memberbrow083312:31 27 Jun '03  
QuestionRe: Found it!sussAnonymous4:19 14 Oct '05  
Generaland you cann't unload the dll???memberfftongzhi0:37 11 Sep '02  
GeneralRe: and you cann't unload the dll???memberfftongzhi19:40 15 Sep '02  
GeneralGood Articlememberjakesher14:00 29 May '02  
GeneralRe: Good ArticlememberNish - Native CPian16:18 29 May '02  
GeneralRe: Good ArticlememberMadhu C17:28 9 Jun '02  
GeneralRe: Good ArticlememberNish - Native CPian18:24 9 Jun '02  
Generalregular dllmemberKannan Kalyanaraman21:47 28 May '02  
GeneralRe: regular dllmemberNish - Native CPian16:19 29 May '02  
GeneralRe: regular dllmemberTaranis10:37 3 Jun '02  
GeneralRe: regular dllmember.dan.g.18:19 16 May '05  
GeneralNext Target -100 ArticlesmemberAmita Butch4:38 28 May '02  
GeneralRe: Next Target -100 ArticlesmemberNish - Native CPian4:44 28 May '02  
GeneralThis completed your half centurymemberRama Krishna3:06 28 May '02  
GeneralRe: This completed your half centurymemberNish - Native CPian4:41 28 May '02  
GeneralRe: This completed your half centurymemberShog912:25 28 May '02  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 May 2002
Editor: Nishant Sivakumar
Copyright 2002 by Nishant Sivakumar
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project