1

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?

13
  • 2
    It will be called as soon as you access an NativeMethods member. Do you call NativeMethods anywhere? Commented Jul 18, 2016 at 21:14
  • 1
    Do you access the NativeMethods class someway? Check this: stackoverflow.com/questions/1437352/… Commented Jul 18, 2016 at 21:15
  • 3
    @Quantic That's a static constructor, as the question says. It's not just a method. Commented Jul 18, 2016 at 21:16
  • 2
    As noted in the marked duplicate, static constructor is called only when you first create an instance of the class or access any static member. A const member is a not a static member, and so doesn't cause the static constructor to be called. And of course, from this you can easily infer that changing the const member to be a static member will ensure that the static constructor is called, but then you'll find you have trouble using that member in the DllImport attribute. Commented Jul 18, 2016 at 21:36
  • 2
    I agree, but the issue is not about static constructors. The actual question is if there is a way to check whether a DllImport file exists or perhaps even how to set the path... and that is where I agree, should be a new question. Commented Jul 18, 2016 at 21:46

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.