Mixed Assembly Not Discovering Native DLLs - c#

I have a mixed mode dll with native dll dependencies.
I am loading the mixed mode dll from a C# exe using Assembly.Load. However, the location of the mixed mode dll is not in the application bin directory, therefore it fails because it only looks for the native C++ dll's in the bin and the folders in the PATH environment variable.
I thought using the option /assemblylinkresource was suppose to stop this and force the native dll's to be found in the alternate directory alongside the deployed mixed mode dll. This is proving to be not correct.
Is there a way to create a multi-file assembly with native dll's using an existing C++/CLI mixed mode dll? The only examples (http://msdn.microsoft.com/en-us/library/xawyf94k(v=vs.100).aspx) I've seen are using .netmodules coupled with a native dll.
Therefore, the solution is to either:
a) some how force the application to search for native dependencies in a directory of your choosing; or
b) package the native dll's into the one managed mixed mode assembly (is this even possible??) - given statically linking the dependencies is not an option.

Normal Windows DLL searching rules apply. So yes, there's no hope it will ever find those DLLs. A "multi-file assembly" isn't going to work either, you cannot merge native code. Options you have, roughly in preferred order:
Call SetDllDirectory() to add the path that contains the DLLs to the set of directories where Windows will look. May fail if the external code uses it as well.
Use Environment.SetEnvironmentVariable() to append the path to the PATH environment variable. This only changes the process' copy of the PATH so is a reasonable approach. May fail on machines that have a bloated PATH that is reaching the limit.
Set Enviroment.CurrentDirectory to the path with the DLLs. May fail if the external code tinkers with it as well.
Record the path for each DLL at install time in the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs registry key.
Install the DLLs in the Windows side-by-side cache and use a manifest to tell Windows about it. This is hard to get right.

Potential candidate for a solution, not tested with MMA: This is probably not the optimal solution you were hoping for, but I thought I would add it as it could help you along the way to achieve solution a). In c++ you could control loading path and path search order by either manually setting the directory to be searched using SetDllDirectory (only available from XP SP1) or by manually loading the dll using LoadLibraryEx.
I guess one could use P/invokes to get access to these calls in C#
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern void SetDllDirectory(string lpPathName);

Related

External DLL write in C and use in C# [duplicate]

I have a dll library with unmanaged C++ API code I need to use in my .NET 4.0 application. But every method I try to load my dll I get an error:
Unable to load DLL 'MyOwn.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I have read and tried several solutions I have found on the internet. Nothing works..
I have tried using following methods:
[DllImport("MyOwn.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs((UnmanagedType.I4))]
public static extern Int32 MyProIni(string DBname, string DBuser_pass,
string WorkDirectory, ref StringBuilder ErrorMessage);
When I tried following this article and when I run this example (from the downloaded code) it runs without a problem (the dll used is in the bin/debug folder)
I have copied my dll (along with all the files the it depends on into my bin folder).
I also tried this approach but got the same error:
[DllImportAttribute(MyOwnLibDllPath, EntryPoint="TMproIni")]
[return: MarshalAs(UnmanagedType.I4)]
public static extern int MyproIni(string DBname, string DBuser_pass,
string WorkDirectory, ref StringBuilder ErrorMessage);
Any suggestions?
From what I remember on Windows the search order for a dll is:
Current Directory
System folder, C:\windows\system32 or c:\windows\SysWOW64 (for 32-bit process on 64-bit box).
Reading from the Path environment variable
In addition I'd check the dependencies of the DLL, the dependency walker provided with Visual Studio can help you out here, it can also be downloaded for free: http://www.dependencywalker.com
You can use the dumpbin tool to find out the required DLL dependencies:
dumpbin /DEPENDENTS my.dll
This will tell you which DLLs your DLL needs to load. Particularly look out for MSVCR*.dll. I have seen your error code occur when the correct Visual C++ Redistributable is not installed.
You can get the "Visual C++ Redistributable Packages for Visual Studio 2013" from the Microsoft website. It installs c:\windows\system32\MSVCR120.dll
In the file name, 120 = 12.0 = Visual Studio 2013.
Be careful that you have the right Visual Studio version (10.0 = VS 10, 11 = VS 2012, 12.0 = VS 2013...) right architecture (x64 or x86) for your DLL's target platform, and also you need to be careful around debug builds. The debug build of a DLL depends on MSVCR120d.dll which is a debug version of the library, which is installed with Visual Studio but not by the Redistributable Package.
The DLL has to be in the bin folder.
In Visual Studio, I add the dll to my project NOT in References, but "Add existing file". Then set the "Copy to Output Directory" Property for the dll to "Copy if newer".
This is a 'kludge' but you could at least use it to sanity-test:
Try hard-coding the path to the DLL in your code
[DllImport(#"C:\\mycompany\\MyDLL.dll")]
Having said that; in my case running dumpbin /DEPENDENTS as suggested by #anthony-hayward, and copying over 32-bit versions of the DLLs listed there into my working directory solved this problem for me.
The message is just a bit misleading, becuase it isn't "my" dll that can't be loaded - it's the dependencies
Try to enter the full-path of the dll.
If it doesn't work, try to copy the dll into the system32 folder.
"Unable to load DLL 'xxx.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)" means the file CAN be found BUT it's not able to load it. Try to copy the DLL file to the root folder of your application, some DLL libraries need to be available in the root folder of the application in order for it to work. Or check if there are any other depending DLL files required by it.
"Cannot find DLL 'xxx.dll': ..." means the file CANNOT be found. Try to check the path. For example, [DllImport(#"\Libraries\Folder\xxx.dll")]
Ensure that all dependencies of your own dll are present near the dll, or in System32.
Turn on the fusion logging, see this question for lots of advice on how to do that. Debugging mixed-mode apps loading problems can be a right royal pain. The fusion logging can be a big help.
Make sure you set the Build Platform Target to x86 or x64 so that it is compatible with your DLL - which might be compiled for a 32 bit platform.
There is one very funny thing (and has a technical relevance) which might waste your hours so thought of sharing it here -
I created a console application project ConsoleApplication1 and a class library project ClassLibrary1.
All the code which was making the p/invoke was present in ClassLibrary1.dll. So before debugging the application from visual studio I simply copied the C++ unmanaged assembly (myUnmanagedFunctions.dll) into the \bin\debug\ directory of ClassLibrary1 project so that it can be loaded at run-time by the CLR.
I kept getting the
Unable to load DLL
error for hours. Later on I realized that all such unmanaged assemblies which are to be loaded need to be copied into the \bin\debug directory of the start-up project ConsoleApplication1 which is usually a win form, console or web application.
So please be cautious the Current Directory in the accepted answer actually means Current Directory of main executable from where you application process is starting. Looks like an obvious thing but might not be so at times.
Lesson Learnt - Always place the unamanaged dlls in the same directory as the start-up executable to ensure that it can be found.
I had the same problem when I deployed my application to test PC. The problem was development PC had msvcp110d.dll and msvcr110d.dll but not the test PC.
I added "Visual Studio C++ 11.0 DebugCRT (x86)" merge module in InstalledSheild and it worked. Hope this will be helpful for someone else.
In my case one unmanaged dll was depending on another which was missing. In that case the error will point to the existing dll instead of the missing one which can be really confusing.
That is exactly what had happen in my case. Hope this helps someone else.
If the DLL and the .NET projects are in the same solution and you want to compile and run both every time, you can right click the properties of the .NET project, Build events, then add something like the following to Post-build event command line:
copy $(SolutionDir)Debug\MyOwn.dll .
It's basically a DOS line, and you can tweak based on where your DLL is being built to.
I think your unmanaged library needs a manifest.
Here is how to add it to your binary. and here is why.
In summary, several Redistributable library versions can be installed in your box but only one of them should satisfy your App, and it might not be the default, so you need to tell the system the version your library needs, that's why the manifest.
Setup: 32-bit Windows 7
Context: Installed a PCI-GPIB driver that I was unable to communicate through due to the aforementioned issue.
Short Answer: Reinstall the driver.
Long Answer:
I also used Dependency Walker, which identified several missing dependency modules. Immediately, I thought that it must have been a botched driver installation. I didn't want to check and restore each missing file.
The fact that I was unable to find the uninstaller under Programs and Features of the Control Panel is another indicator of bad installation. I had to manually delete a couple of *.dll in \system32 and registry keys to allow for driver re-installation.
Issue fixed.
The unexpected part was that not all dependency modules were resolved. Nevertheless, the *.dll of interest can now be referenced.
I have come across the same problem, In my case I had two 32 bit pcs.
One with .NET4.5 installed and other one was fresh PC.
my 32-bit cpp dll(Release mode build) was working fine with .NET installed PC but Not with fresh PC where I got the below error
Unable to load DLL 'PrinterSettings.dll': The specified module could not be
found. (Exception from HRESULT: 0x8007007E)
finally,
I just built my project in Debug mode configuration and this time my
cpp dll was working fine.
Also faced the same problem when using unmanaged c/c++ dll file in c# environment.
1.Checked the compatibility of dll with 32bit or 64bit CPU.
2.Checked the correct paths of DLL .bin folder, system32/sysWOW64 , or given path.
3.Checked if PDB(Programme Database) files are missing.This video gives you ans best
undestand about pdb files.
When running 32-bit C/C++ binary code in 64bit system, could arise this because of platform incompatibility. You can change it from Build>Configuration manager.
I faced the same problem when import C++ Dll in .Net Framework +4, I unchecked Project->Properties->Build->Prefer 32-bit and it solved for me.
It has nothing to do with dependencies if you checked all dependencies and you know you got them all, it has nothing to do with the file being in the wrong directory either or incorrect ARGUMENTS passed to dll, the DLL Fails to load using LoadLibrary itself.. you could check the address returned from LoadLibrary is always 0x0000000 (not loaded).
I couldn't figure this error out either it worked fine on Windows 7, but on Windows 10 it doesn't work. I fixed the problem though it had nothing to do with missing dependencies or Runtime redistributable packs.
The problem was I had to pack the DLL with upx and it started working again.
Something with the file being unpacked and compiled on old Windows XP operating system created a bad PE Header or Bad file format or something, but packing it with UPX did the trick works fine now and the DLL got 3x smaller haha.
I got this error for one C++ project in our solution, and only on our buildmaster's machine. The rest of us could build it with no problem.
In our case it was because that particular project had <WindowsTargetPlatformVersion> in the .vcxproj file set to "10.0" vs. "10.0.18362.0" as in all our other C++ projects.
Not specifying the entire SDK version number seems to have allowed MSBuild to choose the newest(?) SDK and associated build tools.
Our buildmaster likely had the remnants of a newer SDK on his machine, and MSBuild was trying to use it (and thus RC.exe was not found).
In any case, bringing up the project's property page and changing Configuration Properties > General > Windows SDK Version to "10.0.18362.0" (or whichever specific version of the SDK you have installed) for all of the project's configurations/platforms did the trick.

Link dll from subfolders

I have written a C++/CLI wrapper for some unamanaged dll's (OpenCV). Everything works fine until this point. Now I would like to store the dll's in a subfolder, so the final application structure would look like this:
bin\
MainApp.exe
wrapper.dll
Wrapper\library1.dll
Wrapper\library2.dll
Also, I would like to configure this in the Wrapper project, so I don't need to care about this in any other project using wrapper.dll
I have found several posts talking about this, but none of them seems to match my needs:
Setting the path in app.config file: wrapper.dll does not have an
app.config file, and I would have to add this reference in every
executable project using the dll.
Setting AppDomainSetup.PrivateBinPath: this could be a workaround, but I'm
not sure whether it works for unmanaged dll's.
Using ILMerge: Does it work for unmanaged dll's along with C++/CLI dll?
Ideally I am looking for a property in Project settings to add this subfolder, so every Solution including my project will look for the unmanaged dll's in the right folder.
The problem here is that the DLL's are usually loaded by Windows, and they're loaded when your application starts. Windows starts by looking at the EXE, finds what DLL's it needs, loads them, and then continues to load DLL's needed by DLL's. This is not specific to C++ or C#.
.Net does affect DLL loading, but that's not applicable to native DLL's.
So, what can you do? One solution is to not let Windows load your DLL's. Visual Studio has a DelayLoad option. This uses LoadLibrary at runtime. And with dliNotePreLoadLibrary you can control where it's loaded from. Since this happens at runtime from your DLL, the executables don't need to do anything.

Loading C# DLL to C++/CLI - dependencies directory

I wrote a dll c++/cli library which uses my other c# dll library. C++/cli library works fine when I've got c# dll in the same folder as application which calls it. This library will be finally loaded to many applications and a C# dll must not be copied into directory with application. It has to be in the same folder as c++/cli library, but in that cases I've got System.IO.FileNotFoundException.
My suggestion is to load c# library manually or to change path where f.ex. firefox is looking for dependencies, but I tried with LoadLibrary() and Assembly::LoadFrom() methods to force loading from right directory. Of course I added directory path with dll to system PATH.
I work on VS2010.
You don't change the default directory where an application will look for dlls.
At design time put your dll in some well know location, the one you are going to deploy to. Add a reference to it, make sure it's set to Don't copy ever, otherwise it will end up in the bin folder. You have to do this otherwise it won't compile.
When you deploy, you'll need one package to deploy common dlls, and one for each application. Careful you don't create your own version of dll hell, if appA needs an older or new version of the common dll, compared to AppB
Add an AppDomain.AssemblyResolve event to main (for windows app). At run time the event handler will get fired when you reference a type in your dll, and the assembly has not yet been loaded.
In there you load it from the well known location. That usually in config, or in a relative path.
E.g.
AllMyApps
CommonDLLS
MyFirstApp
So the path you load the required common dll from would be "..\CommonDlls\MyCommondll.dll".
NB you will want to secure the dlls in some way, otherwise a bad guy might be able to inject their version of one in to your app, which would be bad...
You can use this mechanism to get the dll from a remote server or a database blob as well.
The simplest case is only a few lines of code, just look the event up. Took me about 15 minutes to get this going in a similar scenario.
Not on this machine though, otherwise I'd have pasted in the code.

Referenced DLL Cannot Be Found When Running Application

I have a weird situation with some code that I inherited at work. Their application is a multi-project solution, with several of the solutions being (code) pieces of the MS Enterprise Library (not sure which version).
They also have an existing C++ (unmanaged) application which has a bunch of DLLs. One of these DLLs is built in a separate solution, both in 64-bit and 32-bit flavours.
The main application has a reference to this DLL, and calls a couple of static functions (I can see intellisense, even). I can compile and build the main application EXEs, but when I run it, I get an exception that this DLL from the unmanaged code (lets call it CPlusPlusCode.dll cannot be found:
FileNotFound Exception was unhandled: Could not load file or assembly 'CPlusPlusCode.dll' or one of its dependencies. The specified module could not be found.
I'm quite stumped, because I can compile the code, see intellisense for the imported classes, and dig into the DLL in the object browser. I even made sure there's a copy in the \bin\Debug folder (although I don't see why that would make a difference). This is for a Windows Forms application.
Also, if it matters, I had some build issues related to x86 vs. x64 for different projects; I think (hope?) that this is not related to that, but I solved that by using the Configuration Manager to build everything as x64.
Check the GAC, and if necessary you might need to add it or register the DLL there.
I had this problem with a project, it all works ok from Visual Studio and most of my times running the project locally on my machine. But because of the unmanaged code I needed specifically allow the project to be executed with correct permission levels.
So have a look in the manifest file, that enough permissions etc exist.

A problem regarding dll inheritance

I have created a dll that will be used by multiple applications, and have created an installer package that installs it to the program files, as well as adds it to the Global Assembly Cache.
The dll itself uses log4net, and requires a xml file for the logging definitions.
Therefore when the installer is run, the following files get copied to the install directory within program files:
The main dll that I developed
- The Log4Net.dll
- the Log4Net.xml file
I am now experiencing a problem. I have created a test console application for experimentation. I have added my dll as a reference, and set the 'local copy' flag to false.
When I compile the test console exe however, I noticed that it has copied the log4net.dll and log4net.xml files to the bin directory. And when running the test console, it appears that it will only work if the log4net.dll is in the same directory as the exe. This is dispite the fact that the test console application does not use log4net, only the dll that was added as a reference does.
Is there some way to have it so that the log4net.dll & xml files used will be the ones that were installed to the program files, rather than any application needed to copy over local copies? The applications that will be using my dll will not be using log4net, only the dll that they are referencing uses it.
Many thanks
Don't install into the Global Assembly Cache! Even if your library dll is used by multiple applications each should have it's own local copy. Otherwise you get into a whole world of pain for saving a few KB of disk space.
Always copy the required dlls locally. If you are really sure that the application won't need it you can simply delete the unnessesary dlls later or don't include them in the installer. But if your application will call ANY reference there it will crash at runtime. So best option is to leave them there (after all they WERE referenced for a reason).
No, it's not possible (at least not without much efford) to have .Net load dlls from arbitrary locations on the disk. And it should be this way (look up DLL-hell if you want to know why).
I suspect your problem is the configuration. You must use fully qualified names if you want it to work from the GAC. As per the documentation at http://logging.apache.org/log4net/release/faq.html:
"When loading an assembly from the GAC the fully qualified assembly name, including the version, culture and public key must be specified. This is in the standard syntax supported by System.Type.GetType. See the next FAQ on how to get the version and public key for an assembly."
I managed to resolve this by adding Log4net.dll to the GAC as well. It will now run without needing a local copy the dll.
It does however require a local copy of the XML file, to correctly log.

Categories