Static constructor is not called

c#

405 просмотра

1 ответ

948 Репутация автора

I have the following class:

 private static class NativeSomeWrapper
   {
       [DllImport(NativeMethods.myCeeLib, EntryPoint = "Get_300_bars",
           CallingConvention = CallingConvention.Cdecl)]
       [return: MarshalAs(UnmanagedType.SysInt)]
       internal static extern IntPtr Get300bars([MarshalAs(UnmanagedType.SysInt)] IntPtr assessment);
   }

And i have a static class that has responsibility to initilize the dll:

internal static class NativeMethods
{
    public const string myCeeLib= "myCeeLib.dll";


    static NativeMethods()
    {
        var path = GetPathToMyCeeLibFile();
        var err = SetPath(path);
        if (err != ErrorCode.Ok)
        {
            throw new FileNotFoundException("Coulnt find myCeeLib file.");
        }
    }
}

The problem is that NativeMethods constructor is not getting called as expected.

How can i make sure that NativeMethods static constructor is called and the path to library file is set correctly?

Автор: persianLife Источник Размещён: 18.07.2016 09:12

Ответы (1)


3 плюса

183280 Репутация автора

The compiler is going to compute the value of that attribute at compile time, so the static constructor isn't running when you execute your program because by the time the application starts the value has already been computed, and you don't need to access the class to get it (thus triggering the static constructor).

Автор: Servy Размещён: 18.07.2016 09:19
Вопросы из категории :
32x32