David Shochet
David Shochet

Reputation: 5375

How can I call SetDllDirectory() before [DllImport]?

I am building a .Net C# library project that needs to make calls to a function from a C++ dll. The C++ dll is located in a "lib" folder in my project. So I use [DllImport]. I need to pass to DllImport a path to C++ dll in the lib folder.

I don't want it to be a hard-coded full path. As I know, I can call SetDllDirectory("lib") to add my lib folder to search. But, if I am not mistaken, SetDllDirectory() should be called before [DllImport]. Where can I be called from? If I do it from the static constructor, it is too late.

Upvotes: 0

Views: 1678

Answers (1)

David Heffernan
David Heffernan

Reputation: 612964

P/invoke DLLs are loaded on demand the first time a call is made to a p/invoke method. So, you just need to make sure that you call SetDllDirectory before the first call to a function in your DLL.

Upvotes: 4

Related Questions