I wrote a Win32-DLL (with clr support in VS 2010/13, c++) as extension for another/old VB6 app and use the opensource-dll PDFSharp.
It works fine, but if the "PDFSharp.dll" removed from Directory the Application crashes if the program try to load my dll.
I want to include the Sharp DLL into mine, so that only one DLL is needed.
I tried to add it to resources, and load/catch the error during run time by
AppDomain^ root = AppDomain::CurrentDomain;
root->CurrentDomain->AssemblyResolve += gcnew ResolveEventHandler(MyResolveEventHandler);
in the first Function that the app calls, but my Problem is, the app/dll crashes before i can handle something.
ILMerge can't help, because it is a Win32/net(clr) DLL not a 100% NET-DLL.
C++/CLI mixed-mode DLLs have two sets of references: the native imports in the PE header, and the .NET assembly references. Problems finding the native imports will cause the symptom you observed, that loading the assembly fails early during load and cannot be intercepted and recovered.
It's not clear to me why the native dependency rules are applicable here. For a true native dependency that needs to be located using an alternate search order under your control, delay-loading could be applied. But that can't be used with a referenced .NET assembly.
In any case, the simplest fix is to not need a separate assembly at all. Your goal is single file deployment, and the ideal single file deployment scenario is when all the code is contained in a single DLL and you don't need to unpack a second file at runtime.
For pure .NET assemblies, there is an ILMerge tool that combines multiple DLLs into a single file. But your case has a C++/CLI mixed mode DLL, not pure MSIL.
Using multiple languages in a native program generally works a little bit differently. Instead of producing a complete executable from each toolset, native code standardizes an object file format (Windows .obj, Linux .o) which all the various toolsets know how to produce, and then the link step can link together object files from a variety of languages. The object files are often bundled into static libraries. (A static library is just an archive of object files, with a symbol index) Because the C++/CLI toolset is patterned on native C++, it uses this model as well.
The .NET version of this language-independent "object file" which can be further linked is a .netmodule file. Internally, it is a .NET assembly without a manifest. Functionally, it acts like a static library. And the C++/CLI link.exe can link together C# (and VB, and F#, etc) .netmodule static libraries together with the C++/CLI object files and static libraries, and native object files and libraries, when it creates the mixed-mode assembly.
This isn't the most straightforward process, because while it is supported by the underlying toolchains, the Visual Studio project options dialog boxes don't have a UI for either creating or consuming .netmodule static libraries.
For the C# side to produce a .netmodule, you should open your .csproj file and change the <OutputType> setting to module. Then reopen the project in Visual Studio and build as usual.
On the C++/CLI side, the project options dialog allows you to customize the compile and link command-lines. Change the linker command to include /link and the name of the .netmodule file.
If you've done it right, the C++/CLI linker will create a single mixed-mode DLL with all the types and code from both the C# and C++/CLI source files. And all the internal usage between C# and C++/CLI will be already resolved, so you won't have to worry about missing dependencies at run time. Well, at least not these dependencies; any you didn't choose to link in will still be handled normally.
Related
The user's main application is ms-access (with ms-sql server). Ton of code in vba.
One of the main features i have to manifest is controlling my client's voip telephony. My plan is to make a COM DLL that the ms-access can use.
As of now, i've managed to write a C# project (vs2019 .net framework) that handles the voip pbx well, using json, and do all missions necessary, such as invoking calls, sending sms, get calls list, recodings list, get recordings wav files and convert them to mp3. I use Newtopsoft.Json and NAudio.Lame.
BUT it only works as a standalone .net project or exe.
As a COM DLL (class library) - ms-access can handle and use it UNTIL it gets to the part where the code uses ANY external dll's functionality - and it crashes (with newtonsoft) or just not working (with naudio), although the dll's are in the working folder.
I know i have to found a way to make these external dll's to work under the office (32bit) enviroment.
I was trying and guessing many code samples for a couple of days. I tried to follow the Assembly.Load/From/File examples to dynamically load and include the dll's, but i failed to assimilate it in my code or even to understand it enough.
I hope i'll get a solution here.
Thanks :)
Hum, I am able to create a COM object for use with Access. External library code (in my case Newton soft) for serializing data works just fine when that class code is used as a COM object from Access.
You don't mention if the other libraries are managed code, or external win32 .dll? I have however used un-managed .dll’s with a .net COM object, and then have consumed that from MS-access.
The only issue would be in project explorer is to ensure that you have a copy local setting = true for the external referenced .net .dll libraries. (And that is the default, so I am sure you do.
The next issue of course is of course is there any use of configuration files? (app.config) etc.? The reason for this of course that since your application is being launched with msaccess.exe, then the config and settings will be assumed to be in the office install folder, and not the local application. As a result, it not all so practical to move/copy those app.config files to the office folder where msaccess.exe resides. And the config file name will not only have to be in the same folder, but also named.
Msaccess.exe.config.
In place of
YourDotNet.exe.config
Now of course, if you build your project as a .net exec? Well then of course any config settings (application ones, not user) will be placed in this config file, and of course that file will have to be placed in the same folder as the .exe file.
So, one might add a “test” function (any function is a method of that class) to the class that you test/call from VBA to ensure that such settings are being seen and read (if you are using any settings).
Eg:
System.Reflection.Assembly.GetExecutingAssembly().Location + ".config"
So, return that to access and display this result.
The other issue is of course to FORCE your project to x86. I would not use “any” CPU. While this “may” work, since you are using access x32, then I would force compile your .net class to x86 as opposed to “any” CPU. This would also spit out some errors in case some of the external assemble(ies) are compared to a particular bit size and thus x86 settings will result in your class not consuming some of the external .net .dll’s.
Now you “note” that your project works as an .exe, and then “sort of” works as a class and “.dll” registered as a COM.
However, you don’t mention how you are “flipping” this from an .exe to a class, or do you simply have a .net “test” project that you run as an .exe, and it of course has a reference to that class .dll. And you NOT using “COM” for this testing.
If your test.exe program can use that external assembly?
Then I would create a test2 project, but this time around do NOT reference the assembly (as .net), but try using .net CreateObject(). (I think c# has this choice – vb.net certainly does).
So you could try + use a CreateObject() in this .net test sample, and thus test from .net as COM.
So this test .net program (one that has NOT referenced the assembly) would a intermediate test before you jump all the way into ms-access + VBA test code.
However, I would first test/check if an app.config file is being used here, since as noted when you flip to a COM object, and then create a instance of that object in Access/VBA?
Then the config file will NOT be used. You can in .net code force/change the app.config file in that running assembly, and I can’t seem to find my code example that does this. But I am not going to dig too hard until such time we confirm that you are using app.exe.config file here.
Edit
Out of cuirous, I googled naudio. It is managed code. So, that library should work just fine. If that project is compiled as "ANY CPU", you COULD try re-compile as x86, and also re-compile your test program as x86. Then when you create a COM object, then again compile that as x86.
As noted, I do quite a bit of COM stuff for ms-access, and I have without issue used Newtonsoft (for jason serializing/de-serializing) as a COM object that is consumed by ms-access.
And given that naudio is managed code then I don't see why it would be an issue. Any other 3rd party .dll's you using here? As a quick test, I would set all projects to x86. You seem to "mention" that "some" of the COM object works, but just not all.
I am attempting to write a a CLI interop layer between an existing c++ codebase and a c# wpf app. My c++ libraries already overload global new and delete in order to implement my own memory tracking and other niceties. So the dependencies look something like this:
(Native library compiled to static lib)->(CLI layer)->(C# WPF application)
However, whenever I include my native libraries and try and build my CLI project, I run into a conflicting symbol for global delete which was already defined in msvcrtd:
Error LNK2005 "void __cdecl operator delete(void *)" (??3#YAXPAX#Z) already defined in msvcrtd.lib(delete_scalar.obj)
I'm not sure how to get my build to take my global delete instead of the one in the default library. I have tried making another pure native project that compiles a DLL, and compiling all of my static libs into that, then having the interop layer load that DLL. This works, but I'd rather not have 2 layers of glue instead of the one.
I'm using visual studio 2015.
The native component uses the CRT as DLL? This is requirement if using mixed assemblies. If you statically linked library uses the static CRT you get into troubles.
Check and link with the /VERBOSE flag to see, where this other delete comes from. Eliminate this other library call.
I have a c++/CLI library that is in turn calling a c# library. That is fine, it is linking implicitly and all is good with the world. But for various reasons the libraries are not getting quite the prefect treatment by our automated build process, and the libraries are not finding each other unless we move the libraries to locations that we would rather not have them in, and would rather not fold into our build process.
It is suggested to me that we/I could write a post-build event that uses XCOPY. but lets say we don't want to do that.
Another suggestion is to explicitly load the dll. Windows says that to link explicitly "Applications must make a function call to explicitly load the DLL at run time." The problem is that Microsoft's example is not enough for my small mind to understand how to proceed with this idea. Worse, the only example I could find is out of date. Perhaps I am not using the right search terms but I am having difficulty finding more about it with google.
How do we explicitly Link a c++/Cli Library to a C# .dll?
----edit
OK, How do we explicitly Link a C++/CLI code, which exports a library using __declspec(), to a C# .dll.
There is no such thing as a "C++/CLI library", only assemblies are supported. There is no explicit or implicit linking, binding always happens at runtime. Assemblies are found at runtime by the CLR, the rules it uses to locate them are described in detail in the MSDN library.
Copying all dependencies into the same directory as the EXE is the sane way to go about it while you are developing the code. Well supported by build system, the C# and C++ rules are however different. C++ projects build to the solution's Debug directory, C# projects build to the EXE project's bin\Debug directory. So yes, altering a C++ project's Output Directory setting or copying files with a post build event is usually required to get everything together.
I have a given code written in unmanaged C++ that I added as a resource in a C# program.
When trying to load the unmanaged EXE using Assembly.Load, I get a BadImageFormatException whose InnerException says that "the IL Format is incorrect" (obviously).
How can I make this work?
I know that using the code as a DLL would be better, but for some reason, the dll call does not behave the same way as when I run the unmanaged exe with System.Diagnostics.Process.Start.
And I don't want to have two separates EXE files. Any idea?
EDIT: OK, I no longer need to do that. My dll behaved a different way because I was using it in a different context (winform instead of console); therefore the function causing the problem, SetThreadDesktop, couldn't work as expected. Gonna close post now, thanks for all those who answered.
You can't load an unmanaged exe/dll with Assembly.Load(), it works only with managed ones. if you need to PInvoke on that unmanaged file, and the reason you want a single exe is just deploy, you can pack it as an embedded resource (as you currently did ) and unpack on the target machine in a file, and use it as usual.
If you have unmanaged DLL as resource - basic steps:
Save resource to disk at run-time
use LoadLibrary (Win32 call to LoadLibrary using PInvoke)
either use methods from this library by calling methods annotated for PInvoke, or manually via GetProcAddress.
Slightly different approach, that could be automated, is using the so-called "assembly weaving"
Costura.Fody - https://github.com/Fody/Costura - is the one of the 'weavers'. The embedding process (with tests automation) for incorporating unmanaged resources and transparently loading them at runtime without much of effort -
Install-Package Fody.Costura
Then all of embedding, unpacking, assembly locating and loading is automated by default, and controlled by including 'FodyWeavers.xml' config, added to your project.
<Costura>
<Unmanaged32Assemblies>
Foo32
Bar32
</Unmanaged32Assemblies>
<Unmanaged64Assemblies>
Foo64
Bar64
</Unmanaged64Assemblies>
</Costura>
The concept behind approach, is static <Module> class loader, that is binary changed by Fody project tasks, after your project assembly was successfully built. Internally Mono.Cecil is used for the static '<Module>' loader injection that unpacks resources automatically, saves them to temporary directory, telling to load dll's from that location, etc. at assembly load event.
I'm getting System.IO.FileNotFoundException: The specified module could not be found when running C# code that calls a C++/CLI assembly which in turn calls a pure C DLL. It happens as soon as an object is instantiated that calls the pure C DLL functions.
BackingStore is pure C.
CPPDemoViewModel is C++/CLI calling BackingStore it has a reference to BackingStore.
I tried the simplest possible case - add a new C# unit test project that just tries to create an object defined in CPPDemoViewModel . I added a reference from the C# project to CPPDemoViewModel .
A C++/CLI test project works fine with just the added ref to CPPDemoViewModel so it's something about going between the languages.
I'm using Visual Studio 2008 SP1 with .Net 3.5 SP1. I'm building on Vista x64 but have been careful to make sure my Platform target is set to x86.
This feels like something stupid and obvious I'm missing but it would be even more stupid of me to waste time trying to solve it in private so I'm out here embarrassing myself!
This is a test for a project porting a huge amount of legacy C code which I'm keeping in a DLL with a ViewModel implemented in C++/CLI.
edit
After checking directories, I can confirm that the BackingStore.dll has not been copied.
I have the standard unique project folders created with a typical multi-project solution.
WPFViewModelInCPP
BackingStore
CPPViewModel
CPPViewModelTestInCS
bin
Debug
Debug
The higher-level Debug appears to be a common folder used by the C and C++/CLI projects, to my surprise.
WPFViewModelInCPP\Debug contains BackingStore.dll, CPPDemoViewModel.dll, CPPViewModelTest.dll and their associated .ilk and .pdb files
WPFViewModelInCPP\CPPViewModelTestInCS\bin\Debug contains CPPDemoViewModel and CPPViewModelTestInCS .dll and .pdb files but not BackingStore. However, manually copying BackingStore into that directory did not fix the error.
CPPDemoViewModel has the property Copy Local set which I assume is responsible for copying its DLL when if is referenced. I can't add a reference from a C# project to a pure C DLL - it just says A Reference to Backing Store could not be added.
I'm not sure if I have just one problem or two.
I can use an old-fashioned copying build step to copy the BackingStore.dll into any given C# project's directories, although I'd hoped the new .net model didn't require that.
DependencyWalker is telling me that the missing file is GPSVC.dll which has been suggested indicates security setting issues. I suspect this is a red herring.
edit2
With a manual copy of BackingStore.dll to be adjacent to the executable, the GUI now works fine. The C# Test Project still has problems which I suspect is due to the runtime environment of a test project but I can live without that for now.
Are the C and C++ DLLs in the same directory as the C# assembly that's executing?
You may have to change your project output settings so that the C# assembly and the other DLLs all end up in the same folder.
I've often used the Dependency Walker in cases like this; it's a sanity check that shows that all the dependencies can actually be found.
Once your app is running, you may also want to try out Process Monitor on the code you are running, to see which DLLs are being referenced, and where they are located.
The answer for the GUI, other than changing output settings, was the addition of a Pre-Build Step
copy $(ProjectDir)..\Debug\BackingStore.* $(TargetDir)
The answer for the Test projects was to add the missing DLL to the Deployment tab of the testrunconfig. You can either do so by directly editing the default LocalTestRun.testrunconfig (appears in Solution under Solution Items) or right-click the Solution and Add a new test run config, which will then appear under the main Test menu.
Thanks for the answers on this SO question on test configurations for leading me to the answer.
The reason why this happens is because you either are loading DLLMAIN from managed code, before the CRT has an opportunity to be initialized. You may not have any managed code, be executed DIRECTLY or INDERECTLY from an effect of DllMain notifications. (See: Expert C++/CLI: .Net for Visual C++ Programmers, chapter 11++).
Or you have no native entrypoint defined wahtsoever, yet you have linked to MSVCRT. The CLR is automatically initialized for you with /clr, this detail causes a lot of confusion and must be taken into account. A mixed mode DLL actually delay loads the CLR through the use of hot-patching all of the managed entry point vtables in your classes.
A number of class initialization issues surround this topic, loader lock and delay loading CLR are a bit trickey sometimes. Try to declare global's static and do not use #pragma managed/unmanaged, isolate your code with /clr per-file.
If you can not isolate your code from the managed code, and are having trouble, (after taking some of these steps), you can also look towards hosting the CLR yourself and perhaps going through the effort of creating a domain manager, that would ensure your fully "in-the-loop" of runtime events and bootstrapping.
This is exactally why, it has nothting todo with your search path, or initialization. Unfortunately the Fusion log viewer does not help that much (which is the usual place to look for .NET CLR assembly binding issues not dependency walker).
Linking statically has nothing todo with this either. You can NOT statically link a C++/CLI application which is mixed mode.
Place your DLLMAIN function into a file by itself.
Ensure that this file does NOT have /CLR set in the build options (file build options)
Make sure your linking with /MD or /MDd, and all your dependencies which you LINK use the exact same CRT.
Evaluate your linker's settings for /DEFAULTLIB and /INCLUDE to identify any possiable reference issues, you can declare a prototype in your code and use /INCLUDE to override default library link resolution.
Good luck, also check that book it's very good.
Make sure the target system has the correct MS Visual C runtime, and that you are not accidentally building the C dll with a debug runtime.
This is an interesting dilemma. I've never heard of a problem loading native .DLLs from C++/CLI after a call into it from C# before. I can only assume the problem is as #Daniel L suggested, and that your .DLL simply isn't in a path the assembly loader can find.
If Daniel's suggestion doesn't work out, I suggest you try statically linking the native C code to the C++/CLI program, if you can. That would certainly solve the problem, as the .DLL would then be entirely absorbed into the C++/CLI .DLL.
Had the same problem switching to 64-bit Vista. Our application was calling Win32 DLLs which was confusing the target build for the application. To resolve it we did the following:
Go to project properties;
Select Build tab;
Change 'Platform target:' option to x86;
Rebuild the application.
When I re-ran the application it worked.