Bruno Klein
Bruno Klein

Reputation: 3367

Generating initialization code for .dll

I recently heard that it is possible for a .dll to run code as soon as it is loaded, when an application which references the .dll is loaded, for example. Event though I made some tests of my own and tried looking for answers here and on Google I was unable to find some way to generate an initialization method for a .dll.

I would like to know if it is really possible to run code from a .dll when it is loaded by an application.

If so, how can I do so?

Upvotes: 10

Views: 9946

Answers (3)

Pragmateek
Pragmateek

Reputation: 13396

WARNING (thanks Ben Voigt for the catch :)): the below code applies only to C# that guarantees that the generated class won't be beforefieldinit. But with C++/CLI should not work as easily: Managed C++ Static Constructor not called in .net4


So as stated in my comment you may use something like this:

using System;

class MyAwesomeLibrary
{
    static MyAwesomeLibrary()
    {
        Console.WriteLine(string.Format("Hey {0} is using me!", Environment.UserName));
    }
    
    public static int GetTheAnswer()
    {
        return 42;
    }
}

class Client
{
    static void Main()
    {
        Console.WriteLine("The answer is: " + MyAwesomeLibrary.GetTheAnswer());
    }
}

In the static constructor you can do advanced things like checking the registry, communicating with a server...

And if you're a bad guy (or just a developer/company who wants to protect its rights) you can throw an exception:

throw new Exception("The library has not been correctly registered...");

This will result in a TypeInitializationException preventing the use of the whole library class.

Or you can implement a CheckMe method ans asks all the user to call it before using the library or even to authenticate and get a security token they'll use each time they use something...

EDIT:

Whatever the protection you use a determined attacker could circumvent all the plumbing by decompiling the library so if you can you should obfuscate your library too to be (a little) more protected.

Upvotes: 8

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

To long for comment...

Note that putting non-trivial code (i.e. slow remote network call) into startup code of any kind (like static constructor of an important class) will alienate users of your library. It may force them to write special code to avoid random delays on load/method call.

Simply having "validate license" method in the library is probbly better solution.

Note that "phone home" feature itself is often not very welcome by users and better be well documented. Especially if you want your library to be usable as part of someone else programs.

Upvotes: 2

Peuczynski
Peuczynski

Reputation: 4733

You can call the dll code in application constructor. This is the point where assemblies are resolved.

Upvotes: -1

Related Questions