1. 程式人生 > 其它 >Walkthrough: Create and use your own Dynamic Link Library (C++)

Walkthrough: Create and use your own Dynamic Link Library (C++)

參考網站:https://docs.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-160

This step-by-step walkthrough shows how to use the Visual Studio IDE to create your own dynamic link library (DLL) written in Microsoft C++ (MSVC). Then it shows how to use the DLL from another C++ app. DLLs (also known asshared libraries

in UNIX-based operating systems) are one of the most useful kinds of Windows components. You can use them as a way to share code and resources, and to shrink the size of your apps. DLLs can even make it easier to service and extend your apps.

In this walkthrough, you'll create a DLL that implements some math functions. Then you'll create a console app that uses the functions from the DLL. You'll also get an introduction to some of the programming techniques and conventions used in Windows DLLs.

This walkthrough covers these tasks:

  • Create a DLL project in Visual Studio.

  • Add exported functions and variables to the DLL.

  • Create a console app project in Visual Studio.

  • Use the functions and variables imported from the DLL in the console app.

  • Run the completed app.

Like a statically linked library, a DLLexports

variables, functions, and resources by name. A client appimportsthe names to use those variables, functions, and resources. Unlike a statically linked library, Windows connects the imports in your app to the exports in a DLL at load time or at run time, instead of connecting them at link time. Windows requires extra information that isn't part of the standard C++ compilation model to make these connections. The MSVC compiler implements some Microsoft-specific extensions to C++ to provide this extra information. We explain these extensions as we go.

This walkthrough creates two Visual Studio solutions; one that builds the DLL, and one that builds the client app. The DLL uses the C calling convention. It can be called from apps written in other programming languages, as long as the platform, calling conventions, and linking conventions match. The client app usesimplicit linking, where Windows links the app to the DLL at load-time. This linking lets the app call the DLL-supplied functions just like the functions in a statically linked library.

This walkthrough doesn't cover some common situations. The code doesn't show the use of C++ DLLs by other programming languages. It doesn't show how tocreate a resource-only DLL, or how to useexplicit linkingto load DLLs at run-time rather than at load-time. Rest assured, you can use MSVC and Visual Studio to do all these things.

For links to more information about DLLs, seeCreate C/C++ DLLs in Visual Studio. For more information about implicit linking and explicit linking, seeDetermine which linking method to use. For information about creating C++ DLLs for use with programming languages that use C-language linkage conventions, seeExporting C++ functions for use in C-language executables. For information about how to create DLLs for use with .NET languages, seeCalling DLL Functions from Visual Basic Applications.

Prerequisites

  • A computer that runs Microsoft Windows 7 or later versions. We recommend Windows 10 for the best development experience.
  • A copy of Visual Studio. For information on how to download and install Visual Studio, seeInstall Visual Studio. When you run the installer, make sure that theDesktop development with C++workload is checked. Don't worry if you didn't install this workload when you installed Visual Studio. You can run the installer again and install it now.

  • An understanding of the basics of using the Visual Studio IDE. If you've used Windows desktop apps before, you can probably keep up. For an introduction, seeVisual Studio IDE feature tour.

  • An understanding of enough of the fundamentals of the C++ language to follow along. Don't worry, we don't do anything too complicated.

Create the DLL project

In this set of tasks, you create a project for your DLL, add code, and build it. To begin, start the Visual Studio IDE, and sign in if you need to. The instructions vary slightly depending on which version of Visual Studio you're using. Make sure you have the correct version selected in the control in the upper left of this page.

To create a DLL project in Visual Studio 2019

  1. On the menu bar, chooseFile>New>Projectto open theCreate a New Projectdialog box.

  2. At the top of the dialog, setLanguagetoC++, setPlatformtoWindows, and setProject typetoLibrary.

  3. From the filtered list of project types, selectDynamic-link Library (DLL), and then chooseNext.

  4. In theConfigure your new projectpage, enterMathLibraryin theProject namebox to specify a name for the project. Leave the defaultLocationandSolution namevalues. SetSolutiontoCreate new solution. UncheckPlace solution and project in the same directoryif it's checked.

  5. Choose theCreatebutton to create the project.

When the solution is created, you can see the generated project and source files in theSolution Explorerwindow in Visual Studio.

Right now, this DLL doesn't do very much. Next, you'll create a header file to declare the functions your DLL exports, and then add the function definitions to the DLL to make it more useful.

To add a header file to the DLL

  1. To create a header file for your functions, on the menu bar, chooseProject>Add New Item.

  2. In theAdd New Itemdialog box, in the left pane, selectVisual C++. In the center pane, selectHeader File (.h). SpecifyMathLibrary.has the name for the header file.

  3. Choose theAddbutton to generate a blank header file, which is displayed in a new editor window.

  4. Replace the contents of the header file with this code:

    C++
    // MathLibrary.h - Contains declarations of math functions
    #pragma once
    
    #ifdef MATHLIBRARY_EXPORTS
    #define MATHLIBRARY_API __declspec(dllexport)
    #else
    #define MATHLIBRARY_API __declspec(dllimport)
    #endif
    
    // The Fibonacci recurrence relation describes a sequence F
    // where F(n) is { n = 0, a
    //               { n = 1, b
    //               { n > 1, F(n-2) + F(n-1)
    // for some initial integral values a and b.
    // If the sequence is initialized F(0) = 1, F(1) = 1,
    // then this relation produces the well-known Fibonacci
    // sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
    
    // Initialize a Fibonacci relation sequence
    // such that F(0) = a, F(1) = b.
    // This function must be called before any other function.
    extern "C" MATHLIBRARY_API void fibonacci_init(
        const unsigned long long a, const unsigned long long b);
    
    // Produce the next value in the sequence.
    // Returns true on success and updates current value and index;
    // false on overflow, leaves current value and index unchanged.
    extern "C" MATHLIBRARY_API bool fibonacci_next();
    
    // Get the current value in the sequence.
    extern "C" MATHLIBRARY_API unsigned long long fibonacci_current();
    
    // Get the position of the current value in the sequence.
    extern "C" MATHLIBRARY_API unsigned fibonacci_index();
    

This header file declares some functions to produce a generalized Fibonacci sequence, given two initial values. A call tofibonacci_init(1, 1)generates the familiar Fibonacci number sequence.

Notice the preprocessor statements at the top of the file. The new project template for a DLL project addsPROJECTNAME_EXPORTSto the defined preprocessor macros. In this example, Visual Studio definesMATHLIBRARY_EXPORTSwhen your MathLibrary DLL project is built.

When theMATHLIBRARY_EXPORTSmacro is defined, theMATHLIBRARY_APImacro sets the__declspec(dllexport)modifier on the function declarations. This modifier tells the compiler and linker to export a function or variable from the DLL for use by other applications. WhenMATHLIBRARY_EXPORTSis undefined, for example, when the header file is included by a client application,MATHLIBRARY_APIapplies the__declspec(dllimport)modifier to the declarations. This modifier optimizes the import of the function or variable in an application. For more information, seedllexport, dllimport.

To add an implementation to the DLL

  1. InSolution Explorer, right-click on theSource Filesnode and chooseAdd>New Item. Create a new .cpp file calledMathLibrary.cpp, in the same way that you added a new header file in the previous step.

  2. In the editor window, select the tab forMathLibrary.cppif it's already open. If not, inSolution Explorer, double-clickMathLibrary.cppin theSource Filesfolder of theMathLibraryproject to open it.

  3. In the editor, replace the contents of the MathLibrary.cpp file with the following code:

    C++
    // MathLibrary.cpp : Defines the exported functions for the DLL.
    #include "pch.h" // use stdafx.h in Visual Studio 2017 and earlier
    #include <utility>
    #include <limits.h>
    #include "MathLibrary.h"
    
    // DLL internal state variables:
    static unsigned long long previous_;  // Previous value, if any
    static unsigned long long current_;   // Current sequence value
    static unsigned index_;               // Current seq. position
    
    // Initialize a Fibonacci relation sequence
    // such that F(0) = a, F(1) = b.
    // This function must be called before any other function.
    void fibonacci_init(
        const unsigned long long a,
        const unsigned long long b)
    {
        index_ = 0;
        current_ = a;
        previous_ = b; // see special case when initialized
    }
    
    // Produce the next value in the sequence.
    // Returns true on success, false on overflow.
    bool fibonacci_next()
    {
        // check to see if we'd overflow result or position
        if ((ULLONG_MAX - previous_ < current_) ||
            (UINT_MAX == index_))
        {
            return false;
        }
    
        // Special case when index == 0, just return b value
        if (index_ > 0)
        {
            // otherwise, calculate next sequence value
            previous_ += current_;
        }
        std::swap(current_, previous_);
        ++index_;
        return true;
    }
    
    // Get the current value in the sequence.
    unsigned long long fibonacci_current()
    {
        return current_;
    }
    
    // Get the current index position in the sequence.
    unsigned fibonacci_index()
    {
        return index_;
    }
    

To verify that everything works so far, compile the dynamic link library. To compile, chooseBuild>Build Solutionon the menu bar. The DLL and related compiler output are placed in a folder calledDebugdirectly below the solution folder. If you create a Release build, the output is placed in a folder calledRelease. The output should look something like this:

Output
1>------ Build started: Project: MathLibrary, Configuration: Debug Win32 ------
1>pch.cpp
1>dllmain.cpp
1>MathLibrary.cpp
1>Generating Code...
1>   Creating library C:\Users\username\Source\Repos\MathLibrary\Debug\MathLibrary.lib and object C:\Users\username\Source\Repos\MathLibrary\Debug\MathLibrary.exp
1>MathLibrary.vcxproj -> C:\Users\username\Source\Repos\MathLibrary\Debug\MathLibrary.dll
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

Congratulations, you've created a DLL using Visual Studio! Next, you'll create a client app that uses the functions exported by the DLL.

Create a client app that uses the DLL

When you create a DLL, think about how client apps may use it. To call the functions or access the data exported by a DLL, client source code must have the declarations available at compile time. At link time, the linker requires information to resolve the function calls or data accesses. A DLL supplies this information in animport library, a file that contains information about how to find the functions and data, instead of the actual code. And at run time, the DLL must be available to the client, in a location that the operating system can find.

Whether it's your own or from a third-party, your client app project needs several pieces of information to use a DLL. It needs to find the headers that declare the DLL exports, the import libraries for the linker, and the DLL itself. One solution is to copy all of these files into your client project. For third-party DLLs that are unlikely to change while your client is in development, this method may be the best way to use them. However, when you also build the DLL, it's better to avoid duplication. If you make a local copy of DLL files that are under development, you may accidentally change a header file in one copy but not the other, or use an out-of-date library.

To avoid out-of-sync code, we recommend you set the include path in your client project to include the DLL header files directly from your DLL project. Also, set the library path in your client project to include the DLL import libraries from the DLL project. And finally, copy the built DLL from the DLL project into your client build output directory. This step allows your client app to use the same DLL code you build.

To create a client app in Visual Studio

  1. On the menu bar, chooseFile>New>Projectto open theCreate a new projectdialog box.

  2. At the top of the dialog, setLanguagetoC++, setPlatformtoWindows, and setProject typetoConsole.

  3. From the filtered list of project types, chooseConsole Appthen chooseNext.

  4. In theConfigure your new projectpage, enterMathClientin theProject namebox to specify a name for the project. Leave the defaultLocationandSolution namevalues. SetSolutiontoCreate new solution. UncheckPlace solution and project in the same directoryif it's checked.

  5. Choose theCreatebutton to create the client project.

A minimal console application project is created for you. The name for the main source file is the same as the project name that you entered earlier. In this example, it's namedMathClient.cpp. You can build it, but it doesn't use your DLL yet.

Next, to call the MathLibrary functions in your source code, your project must include theMathLibrary.hfile. You could copy this header file into your client app project, then add it to the project as an existing item. This method can be a good choice for third-party libraries. However, if you're working on the code for your DLL and your client at the same time, the header files could get out of sync. To avoid this issue, set theAdditional Include Directoriespath in your project to include the path to the original header.

To add the DLL header to your include path

  1. Right-click on theMathClientnode inSolution Explorerto open theProperty Pagesdialog.

  2. In theConfigurationdrop-down box, selectAll Configurationsif it's not already selected.

  3. In the left pane, selectConfiguration Properties>C/C++>General.

  4. In the property pane, select the drop-down control next to theAdditional Include Directoriesedit box, and then chooseEdit.

  5. Double-click in the top pane of theAdditional Include Directoriesdialog box to enable an edit control. Or, choose the folder icon to create a new entry.

  6. In the edit control, specify the path to the location of theMathLibrary.hheader file. You can choose the ellipsis (...) control to browse to the correct folder.

    You can also enter a relative path from your client source files to the folder that contains the DLL header files. If you followed the directions to put your client project in a separate solution from the DLL, the relative path should look like this:

    ..\..\MathLibrary\MathLibrary

    If your DLL and client projects are in the same solution, the relative path might look like this:

    ..\MathLibrary

    When the DLL and client projects are in other folders, adjust the relative path to match. Or, use the ellipsis control to browse for the folder.

  7. After you've entered the path to the header file in theAdditional Include Directoriesdialog box, choose theOKbutton. In theProperty Pagesdialog box, choose theOKbutton to save your changes.

You can now include theMathLibrary.hfile and use the functions it declares in your client application. Replace the contents ofMathClient.cppby using this code:

C++
// MathClient.cpp : Client app for MathLibrary DLL.
// #include "pch.h" Uncomment for Visual Studio 2017 and earlier
#include <iostream>
#include "MathLibrary.h"

int main()
{
    // Initialize a Fibonacci relation sequence.
    fibonacci_init(1, 1);
    // Write out the sequence values until overflow.
    do {
        std::cout << fibonacci_index() << ": "
            << fibonacci_current() << std::endl;
    } while (fibonacci_next());
    // Report count of values written before overflow.
    std::cout << fibonacci_index() + 1 <<
        " Fibonacci sequence values fit in an " <<
        "unsigned 64-bit integer." << std::endl;
}

This code can be compiled, but not linked. If you build the client app now, the error list shows several LNK2019 errors. That's because your project is missing some information: You haven't specified that your project has a dependency on theMathLibrary.liblibrary yet. And, you haven't told the linker how to find theMathLibrary.libfile.

To fix this issue, you could copy the library file directly into your client app project. The linker would find and use it automatically. However, if both the library and the client app are under development, that might lead to changes in one copy that aren't shown in the other. To avoid this issue, you can set theAdditional Dependenciesproperty to tell the build system that your project depends onMathLibrary.lib. And, you can set anAdditional Library Directoriespath in your project to include the path to the original library when you link.

To add the DLL import library to your project

  1. Right-click on theMathClientnode inSolution Explorerand choosePropertiesto open theProperty Pagesdialog.

  2. In theConfigurationdrop-down box, selectAll Configurationsif it's not already selected. It ensures that any property changes apply to both Debug and Release builds.

  3. In the left pane, selectConfiguration Properties>Linker>Input. In the property pane, select the drop-down control next to theAdditional Dependenciesedit box, and then chooseEdit.

  4. In theAdditional Dependenciesdialog, addMathLibrary.libto the list in the top edit control.

  5. ChooseOKto go back to theProperty Pagesdialog box.

  6. In the left pane, selectConfiguration Properties>Linker>General. In the property pane, select the drop-down control next to theAdditional Library Directoriesedit box, and then chooseEdit.

  7. Double-click in the top pane of theAdditional Library Directoriesdialog box to enable an edit control. In the edit control, specify the path to the location of theMathLibrary.libfile. By default, it's in a folder calledDebugdirectly under the DLL solution folder. If you create a release build, the file is placed in a folder calledRelease. You can use the$(IntDir)macro so that the linker can find your DLL, no matter which kind of build you create. If you followed the directions to put your client project in a separate solution from the DLL project, the relative path should look like this:

    ..\..\MathLibrary\$(IntDir)

    If your DLL and client projects are in other locations, adjust the relative path to match.

  8. Once you've entered the path to the library file in theAdditional Library Directoriesdialog box, choose theOKbutton to go back to theProperty Pagesdialog box. ChooseOKto save the property changes.

Your client app can now compile and link successfully, but it still doesn't have everything it needs to run. When the operating system loads your app, it looks for the MathLibrary DLL. If it can't find the DLL in certain system directories, the environment path, or the local app directory, the load fails. Depending on the operating system, you'll see an error message like this:

One way to avoid this issue is to copy the DLL to the directory that contains your client executable as part of the build process. You can add aPost-Build Eventto your project, to add a command that copies the DLL to your build output directory. The command specified here copies the DLL only if it's missing or has changed. It uses macros to copy to and from the Debug or Release locations, based on your build configuration.

To copy the DLL in a post-build event

  1. Right-click on theMathClientnode inSolution Explorerand choosePropertiesto open theProperty Pagesdialog.

  2. In theConfigurationdrop-down box, selectAll Configurationsif it isn't already selected.

  3. In the left pane, selectConfiguration Properties>Build Events>Post-Build Event.

  4. In the property pane, select the edit control in theCommand Linefield. If you followed the directions to put your client project in a separate solution from the DLL project, then enter this command:

    xcopy /y /d "..\..\MathLibrary\$(IntDir)MathLibrary.dll" "$(OutDir)"

    If your DLL and client projects are in other directories, change the relative path to the DLL to match.

  5. Choose theOKbutton to save your changes to the project properties.

Now your client app has everything it needs to build and run. Build the application by choosingBuild>Build Solutionon the menu bar. TheOutputwindow in Visual Studio should have something like the following example depending on your version of Visual Studio:

Output
1>------ Build started: Project: MathClient, Configuration: Debug Win32 ------
1>MathClient.cpp
1>MathClient.vcxproj -> C:\Users\username\Source\Repos\MathClient\Debug\MathClient.exe
1>1 File(s) copied
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

Congratulations, you've created an application that calls functions in your DLL. Now run your application to see what it does. On the menu bar, chooseDebug>Start Without Debugging. Visual Studio opens a command window for the program to run in. The last part of the output should look like:

Press any key to dismiss the command window.

Now that you've created a DLL and a client application, you can experiment. Try setting breakpoints in the code of the client app, and run the app in the debugger. See what happens when you step into a library call. Add other functions to the library, or write another client app that uses your DLL.

When you deploy your app, you must also deploy the DLLs it uses. The simplest way to make the DLLs that you build, or that you include from third parties, available is to put them in the same directory as your app. It's known asapp-local deployment. For more information about deployment, seeDeployment in Visual C++.

See also

Calling DLL Functions from Visual Basic Applications