0

I'm loading a dll with DllImport and the name of the dll (as it is in the same folder as my application):

[DllImport("myDll.dll")]

and till here all works fine if application is opened from the same location. But if I run cmd and type:

"C:\path\to\my\application\app.exe"

the application opens but the dll called from the application itself isn't loaded anymore.

So to sum up if I open manually app.exe from C:\path\to\my\application\ the DllImport works fine and loads the dll in the same path. If I open the application from another location, it isn't loaded anymore.

Any suggestions? Tried also

[DllImport("C:\\path\\to\\my\\application\\myDll.dll")]

and

[DllImport("\\myDll.dll")]

but no way, it doesn't work.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
xpirt
  • 30
  • 1
  • 7

1 Answers1

0

The DLL is located using the DLL search order, as described here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586.aspx. Since the DLL is in the same directory as the executable, it will be found because the directory containing the executable is the first place that the system searches.

So we can conclude that the DLL is found by the loader. Since you report that the behaviour changes when the working directory changes it would seem that is the problem. Your DLL has a dependency on the working directory. It's probably a mistake to have such a dependency. You should find a way to avoid such a dependency.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • the dll itself loads some files from the same directory too – xpirt Nov 30 '14 at 14:47
  • Well there's your problem right there. It's exactly as I said. You might want to use `GetModuleFileName` to locate the directory to load these files from. – David Heffernan Nov 30 '14 at 14:48
  • Sure it can. You just need to be more precise about locating them. As my comment above says. Another option might be to link the files to the dll as resources. – David Heffernan Nov 30 '14 at 14:50
  • to link the files to the dll as resources you mean in the c++ code or in c#? – xpirt Nov 30 '14 at 14:54
  • Presumably to the DLL because it's reading them. Remember you gave no details of this in the question. I don't think I can say much more. – David Heffernan Nov 30 '14 at 16:10