0

this question in my opinion straightforward.

How can I catch an DllNotFoundException in C# as it is just an attribute to some methods use like this:

[DllImport("NativeLib.dll")]    
private static extern void print_line(string str);

When are these functions being invoked ? As I instance the class containing the methods ( sounds odd to me as it's being "static" )? Or as I want to use the methods?

closed as off-topic by Jim G., user40980, gnat, Bart van Ingen Schenau, Avner Shahar-Kashtan Jun 19 '14 at 11:04

  • This question does not appear to be about software engineering within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    Are you actually getting an exception? If so, when? Or is this just theoretical? – Bobson Jun 18 '14 at 21:43
3

In c# static constructors for a class don't run until you use the class for the first time. So if you want to catch the DllNotFoundException you need to do it the first time the class is used. The most convenient way to do this is probably to encapsulate the external function pointer inside a (temporary) nested class, like so, so the external DLL is not loaded until the specific call is made:

public class MyOuterClass
{
    class ExternalDllSubClass
    {
        [DllImport("BananaquitFluffernutterOrWhatever.dll")]
        private static extern void print_line(string str);

        internal static void PrintLine (string str) {
            print_line(str);
        }
    }

    public void PrintLine(string str)
    {
        try
        {
            ExternalDllSubClass.PrintLine(str);
        }
        catch (DllNotFoundException e)
        {
            Debug.WriteLine(e.ToString());
        }
    }

Then just set a break at the beginning of the outer function. (Or catch the DllNotFoundException exception in Visual Studio using the exception assistant.)

For more, see here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.