How are DLLs created out of C++ source, and how are they used in other sources? - c++

How are DLLs created out of C++ source code, and how are they used in other sources?

The DLL is a 'Dynamic Link Library' which works a lot like other libraries but is not linked with your executable application. At run time you can call specific functions for loading your DLL and executing its exported methods.
You can try creating a DLL yourself- create a project using visual studio and specify a DLL. This will create some of the base constructs for your project such as settings for your project to compile the DLL and also some base code for exposing methods, objects, or variables.
There are many walk through's to help you at this point: check here.
So, to summarize:
A DLL is a library which you can be loaded at runtime. This is a very flexible 'plug-in' model. Example: You can programmatically select and load different DLL at runtime. Each DLL can be a 'plug-in' to provide different functionality.
A DLL Has an entry point. Just like your Main function of your command line executable is the entry point, the DLL has an entry point function which is called when different events occur on the DLL such as loading, unloading, and more.
To use a DLL you must use the exported objects or methods of the DLL.
When Calling these exported functions from another application it is very important that you match compatible types! Also, make sure the calling conventions are compatible

Related

What is Different Between "MFC DLL" and "Console Application DLL"?

What is the difference between creating a MFC DLL from Visual Studio wizard and creating C++ Console Application and changing the configuration type to DLL instead of .exe?
You can surely figure out how to change a console application to dll type, but it's recommended to use the non-MFC DLL project template.
One major difference between a non-MFC and a MFC Extension DLL is that it would allow sharing resources like dialog templates or bitmaps to MFC appliactions by calling
// MFC extension DLL one-time initialization
AfxInitExtensionModule(PROJNAMEDLL, hInstance);
// Insert this DLL into the resource chain
new CDynLinkLibrary(Dll3DLL);
in DllMain(). Other benefits are that you can use MFC (CObject-derived) classes that sit in the dll and that the MFC Extension DLL can share the memory address space with the calling instance, meaning that two apps loading the same extension DLL will only share the code but won't interfere with allocated data.
Note that you need the "shared MFC DLL" project setting to use extension DLLs. Linking MFC statically into your project won't work. So extension DLLs aim at sharing code among different apps that run simultaneously, for example, but only use the code memory once. This way of code reuse was one intention at least when extension DLLs were introduced, but in the real world different apps tend to use different versions (dll hell, side-by-side). Speaking of:
One good use of an extension DLL is to customize an app (branding, localisation) just by installing differend versions of a dll.
Further reading: https://learn.microsoft.com/en-us/cpp/build/extension-dlls
According to Creating an MFC DLL Project it states:
An MFC DLL is a binary file that acts as a shared library of functions that can be used simultaneously by multiple applications. The easiest way to create an MFC DLL project is to use the MFC DLL Wizard.
This article Kinds of DLLs also states:
Using Visual Studio, you can build Win32 DLLs in C or C++ that do not
use the Microsoft Foundation Class (MFC) library. You can create a
non-MFC DLL project with the Win32 Application Wizard.
The MFC library itself is available, in either static link libraries
or in a number of DLLs, with the MFC DLL Wizard. If your DLL is using
MFC, Visual Studio supports three different DLL development scenarios ...
I believe the above explains the difference:
One version of the DLL exposes the MFC library.
One version does not.
That is my understanding.
Other related article: Create C/C++ DLLs in Visual Studio
An MFC DLL is a dynamic library that uses MFC components and the MFC runtime. This means that an MFC dynamic library usually requires the MFC support libraries along with the MFC runtime. To compile an MFC DLL requires the MFC include files and the MFC directives.
When you use the Visual Studio Wizard to create an MFC DLL all the compiler, linker, and other settings and options needed to create an MFC DLL are all generated for you along with an MFC DLL stub.
A Console Application is an application that uses the C++ Runtime from a console window.
When you use the Visual Studio Wizard to create a Console Application all the compiler, linker, and other settings and options to create a Console Application are all generated for you with a Console Application stub which is typically a Hello World type of application with a main() that contains a printf().
The source code for a DLL has required structure for a DLL main entry point that is different from the required structure for a Console Application main entry point. See the Microsoft article DllMain entry point which has this example source code:
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpReserved ) // reserved
{
// Perform actions based on the reason for calling.
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
// Initialize once for each new process.
// Return FALSE to fail DLL load.
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
break;
}
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
So the differences between an MFC DLL and a Console Application involves a number of areas:
the structure of the source code
the include files used in the compile
the libraries used in the link
the options used in the compile
the options used in the link
Changing the configuration type does not modify the source code or include files specified in the source code. Nor does changing the configuration type change all of the necessary compiler and linker options and property settings that need to be changed.
See this Microsoft article, DLLs and Visual C++ run-time library behavior, that discusses the structure of DLLs and their run time behavior which provides an idea as to the differences between an EXE and a DLL.
An Application (executable) is a module that can be run. It contains one entrypoint, the main() (console) or WinMain() (windows GUI) function. A running instance of an executable is called a "process" in Win32.
A DLL is a library, intended for use by other applications. It is loaded at runtime - "dynamically", hence the name. DLLs contain no main entrypoint, instead they "export" functions or even classes and data. Lacking a main entrypoint, DLLs cannot be run stand-alone, instead they are "loaded into a process's (application's) address-space". The process can use their exported items. It is a good way to implement commonly used operations, for example a company's "development environment" or "foundation" - SDKs are typically implemented as DLLs.
MFC is a C++ library containing GUI (and other) classes and functions, largely (but not exclusively) wrapping Win32 objects. An application or DLL can be using the MFC library, or not.
As for your question, creating a console application and then changing it to DLL makes no sense. The Wizard will create a main() function, which you will have to manually remove. And finally you will have what, a normal DLL... You can simply create a DLL from the start, whether it will be using MFC or not.
EDIT:
According to the documentation from Microsoft:
Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.
So yes, processes need to contain at least one thread - terminating the primary thread also terminates the process. Furthermore, an executable must contain an entry point, it's what the primary thread will execute and return a value to the system. It's actually impossible to build an executable without a main()/WinMain() function, it will generate Linker Error LNK1561:
entry point must be defined
The linker did not find an entry point, the initial function to call in your executable. By default, the linker looks for a main or wmain function for a console app, a WinMain or wWinMain function for a Windows app, or DllMain for a DLL that requires initialization. You can specify another function by using the /ENTRY linker option.
As for DLLs, the term dynamic "linking" is indeed used by MS, however only to highlight the differences to static linking (what most developers consider linking). It's not linking in the usual way, ie resolving externals, changing symbol names to addresses, performing fixups and the like. A DLL has no unresolved externals and the so called "linking" means just locating exported items from the loaded DLLs (in the case of using an import library they are also assigned to local functions) - the linker is not involved in the procedure. Further information here.
Therefore I don't think that there was something "slightly wrong" in what I had posted above, and certainly not "literally everything".
As for whether my answer should be considered useful or not, I think I was right to suggest not creating an executable and changing it to a dll. An MFC DLL is a DLL "based on" (using) the MFC library - this was clear in my first post. The OP didn't ask about MFC extension DLLs particularly.

Problem with DLL which depend on another DLLs

I created GUI in C# as gui.dll and create C++/CLI interop interop.dll for C++ project. That means (*.exe call --> interop.dll and interop.dll call --> gui.dll) I test it with C++ console application which is working wintout any problem, because in the end consoleApp.exe and all dlls are in same folder.
What I did:
interop is c++/cli code with reference to C# dll. I created class and export it for use it inside plugin.vst3. C# dll is dynamicaly linked
inside plugin.vst3 project I includeLibrary for interop project to use class and add interop.lib to Linker. interop.dll is dynamicaly linked
What I want:
Now I want use those dlls (gui.dll and interop.dll) inside c++ project as another "dll" myPlugin.vst3 (audio plugin). For those who don't know, audio plugins are located on different location as program which use it. That means, if audio program load plugin, it is different scenario as my consoleApp.exe call dll on same location.
The Problem:
When I run host program which load my vst3, unfortunately vst3 start search for my dlls from AudioHost.exe view not from vst3 view where is my vst3 file located.
For example, if myPlugin.vst3 is inside D:\VstiPlugins\MyTest\, interop.dll is on D:\VstiPlugins\interop.dll and gui.dll next to C:\ProgramFiles\Reaper\Reaper.exe, my plugin is loaded. All files myPlugin.vst3, interop.dll and gui.dll must be on same location D:\VstiPlugins\MyTest.
The questions:
Simple question is "How to load those dlls from vst3" as I describe it in "What I want" and "The Problem"?
What come to mind as firstly was load plugin with code (like LoadLibrary(...)) instead use *.lib. But all examples and solutions, are for dlls which export only C functions and not as my scenario where I use class. Can be dll loaded from code and use class?
Another idea was DLL redirection with manifest file, but there is no documentation for that scenario or I can't find it. And I am not sure if it will be working.

Creating a .dll out of existing code

This is a newbie request. I'm looking for materials on .dll creation. Specifially, i want to create a .dll out of a simple 3D engine i've made to learn about the process. I need information on dynamic link libraries that go deeper than the wikipedia page, how are they created, what's necessary, how to create different .dll files for "debug" and "release", how to create a PDB file for it and how to create a header file that'll allow for easy usage of the library from a, f.e., C++ program. Material with strong theoretical side (not as much, "how to create a dynamic link library in visual studio") would be great.
Please share good materials on the subject, all i can find is some information here and there and it doesn't paint the picture for me.
Reading between the lines, I think you really want to know about libraries in general rather than dll's specifically. A library is simply a handy package of object (compiled) code, along with some information about how to call into it. In C++, this usually takes the form of a .h file.
With static libraries (.lib), the linker pulls in the code it needs in exactly the same way as it does with all the rest of your classes. A normal class will get compiled to object code (MyClass.obj), and when they're all done the linker sticks them all together and wires up any inter-object calls with the appropriate addresses. It's the identical process with .lib library files. You end up with a big ball of executable code which includes both your classes, and the library functions within it.
With a dynamic library (.dll), the only difference is that the linking (wiring) happens at runtime instead of at compile time, and the library object code remains in a separate ball - the dll file. When you compile your exe, all calls that use functions in the library are mapped to a stub function. When Windows loads the dll for you, it will stick the dll code into the same memory area as your process, and wire up the stub functions to the real functions that are now available.
The only other difference is that a dll must expose a function that Windows can call when it loads or unloads the dll, in case the dll wants to do any initial setting up / clearing down. This is traditionally called DllMain().
If you want to learn about libraries, I would concentrate on creating a static .lib first before worrying about dll's. This is where most of the work is. Once you have a lib it is child's play to turn it into a dll.
The main thing you need to think about when creating a library is how you are going to expose your API (Application Programming Interface). This is just which functions/classes you are going to expose to the people using your library. You don't have to expose them all, but you do have to decide WHAT to expose. Are you just going to expose some C style functions, or are you going to expose entire objects? This is the real challenge when designing a library. You should try and make your API as easy to use, and obvious as possible if people (and you!) are going to find your library useful.
As for pdb files, differently named release/debug modules, and creating .h files. These are identical to when doing so in an exe.
1) Create a new DLL project, using VS wizard.
2) Add your existing source files to it.
3) Put into *.def file (which should have been created by the wizard) the names of the functions that you want to export from your DLL, as described here.
Basically, that's it. Debug and release configurations are automatically created by the wizard, but if you want the 2 variants to be named differently, you can change their output names: go to Project Properities -> Configuration Properties -> General -> Target name.

C++ windows dll viewer

I want to emulate an unmanaged dll in c++. Is there a good tool to open and view it's interface?
Thanks
The most commonly used tool is Dependency Walker. This shows the list of exported symbols.
However, it does not show the function prototypes because they are not contained in the DLL meta data. To get that information you need a header file for the DLL. The exception to this statement are DLLs containing a COM/ActiveX component with a type library.
And even if you do have the prototypes, that's not enough to know how to emulate the DLL. You need full documentation for the DLL. And then you probably still have a lot of reverse engineering to do.

How to link a .DLL statically?

We have a (pure native C++) .DLL that is build by VS. As clients we have some native C++ applications and a .Net-Wrapper around this DLL written in C++/CLI. Finally there are some client applications for the .Net-Wrapper written in C#.
My problem is that the native.dll must be distributed in a different way than the .Net world works and the VS does not keeps track of that DLL.
So to let all my C# Apps work correctly I have to copy it to each executable directory or put it somwhere in %PATH% (which I would avoid on developer computers since they may want to start different apps with different versions of the DLL).
Even bigger problems occur if there are UserControls that reference the Wrapper-DLL: You have to copy the DLL to VS's directory or again to %PATH%.
But the worst case occurs with our Translator tool. This tool keeps track of .Net-Assemblies and packs them into Translator-packages that can be send to an external translator. As far as I know there is no way to put the native .DLL into that package!
So I plan to link the native DLL statically into the .Net-Wrapper which would solve my problems.
But for our Native applications this native DLL must still be a DLL.
So I have two options:
Make two projects of that (one that generates a static library; and one that creates a dynamic one => I try to avoid this)
Find a solution to link DLLs statically
Find a way to let VS generate two outputs from one project
In the C++ project file for the dll, create two configurations, one that generates a DLL and one that generates a .lib. Two projects are not necessary, since any .NET/C++ project can support multiple build configurations (this is how Release and Debug versions build differently).
Another option is to have two projects, one project will output a .lib which can be statically linked, and a second project which will output a .dll and will have your .lib as dependency, you should add .def to your .dll with the symbols that you are planning to export, or else it will be empty.
Pick up a copy of DLL to Lib (Edit: If you can't find a cheaper option)
You can generate a dll and export the entry point to a lib using dllexport, this is explained here
http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx