0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
David Shochet
  • 5,035
  • 11
  • 57
  • 105
  • The Main() entrypoint would be a good choice. But no guarantee that it is early enough, the just-in-time compiler has to compile Main() before it can start running and that might slurp a [DllImport], particularly in the Release build. You then have to delay the execution of your real Main() body by moving it into another static method that you attribute with [MethodImpl(MethodimplOptions.NoIlining)]. Next you'd have to fret over static variables with an initializer, drop the initializer. Next you'd have to wonder a bit if this kind of flexibility is a wise choice. – Hans Passant Jul 16 '18 at 17:31
  • But I am building a dll, and would like to have it independent from the host project. So there is no Main() available... – David Shochet Jul 16 '18 at 19:55
  • 1
    It is the programmer that provides the EXE that is going to deploy these DLLs. Your own DLL has no decent way to guess what he'll do, it is not your call. Forcing the OS to look in the same directory as the managed DLL with SetDllDirectory is not entirely illogical, but do be aware that it suffers badly from the "what if two people do this and they don't know each other" problem. Deploying everything in one directory is the universal and trouble-free recommendation. If the EXE creator wants something else then he can do that himself. – Hans Passant Jul 16 '18 at 20:23
  • Thank you for the explanation! – David Shochet Jul 17 '18 at 14:27

1 Answers1

4

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490