Creating and Using a Managed Assembly (C+)

The next type of library that we will create is a managed assembly. Using managed assemblies is a great way to reuse code. Rather than re-implementing the same routines in every program that you create, you write them once and reference them from applications that need the functionality.

This walkthrough covers the following:

  • Creating a new class library project.

  • Adding a class to the class library.

  • Creating an application that references the class library.

  • Using the functionality from the class library in the console application.

  • Running the application.

Prerequisites

This topic assumes that you understand the fundamentals of the C++ language.

To create a new class library project

  1. From the File menu, select New and then select Project….

  2. On the Project types pane, under Visual C++, select CLR. This creates a project that targets the common language runtime.

  3. On the Templates pane, select Class Library.

  4. Choose a name for the project, such as MathFuncsAssembly, and type it in the Name field. Choose a name for the solution, such as ManagedAssemblies, and type it in the Solution Name field.

  5. Press OK to create the project.

  6. By default, when new projects are created, they are set up to use precompiled headers. To disable precompiled header, select Properties from the Project menu. Expand the Configuration Properties node, expand the C/C++ node, and then select Precompiled Headers. From the dropdown list next to Create/Use Precompiled Header, select Not Using Precompiled Header. Press OK to save these changes. For more information on precompiled headers, see Creating Precompiled Header Files.

To add a class to the class library

  1. After you create a new CLR Class Library, the wizard generates a simple class for you. The names for the header file and source file will be the same as the name you chose for the project earlier. In this example, they are named MathFuncsAssembly.h and MathFuncsAssembly.cpp.

  2. Replace the existing code in MathFuncsAssembly.h with a simple class that is named MyMathFuncsAssembly to do common mathematical operations, such as addition, subtraction, multiplication, and division. The code should resemble the following:

    // MathFuncsAssembly.h
    
    using namespace System;
    
    namespace MathFuncs
    {
        public ref class MyMathFuncs
        {
        public:
            // Returns a + b
            static double Add(double a, double b);
    
            // Returns a - b
            static double Subtract(double a, double b);
    
            // Returns a * b
            static double Multiply(double a, double b);
    
            // Returns a / b
            // Throws DivideByZeroException if b is 0
            static double Divide(double a, double b);
        };
    }
    
  3. Implement the functionality for MyMathFuncs in the source file. The code should resemble the following:

    // MathFuncsAssembly.cpp
    // compile with: /clr /LD
    
    #include "MathFuncsAssembly.h"
    
    namespace MathFuncs
    {
        double MyMathFuncs::Add(double a, double b)
        {
            return a + b;
        }
    
        double MyMathFuncs::Subtract(double a, double b)
        {
            return a - b;
        }
    
        double MyMathFuncs::Multiply(double a, double b)
        {
            return a * b;
        }
    
        double MyMathFuncs::Divide(double a, double b)
        {
            if (b == 0)
            {
                throw gcnew DivideByZeroException("b cannot be zero!");
            }
    
            return a / b;
        }
    }
    
  4. Compile the class library by selecting Build Solution from the Build menu. This creates a dynamic link library (DLL) that can be used by other programs. For more information on DLLs, see DLLs.

To create an application that references the class library

  1. To create an application that will reference and use the class library that you just created, from the File menu, select New and then select Project….

  2. On the Project types pane, under Visual C++, select CLR. This creates a project that targets the Common Language Runtime.

  3. On the Templates pane, select CLR Console Application.

  4. Choose a name for the project, such as MyExecRefsAssembly, and type it in the Name field. Next to Solution, select Add to Solution from the drop down list. This will add the new project to the same solution as the class library.

  5. Press OK to create the project.

  6. By default, when new projects are created, they are set up to use precompiled headers. To disable precompiled header, select Properties from the Project menu. Expand the Configuration Properties node, expand the C/C++ node, and then select Precompiled Headers. From the dropdown list next to Create/Use Precompiled Header, select Not Using Precompiled Header. Press OK to save these changes. For more information on precompiled headers, see Creating Precompiled Header Files.

To use the functionality from the class library in the console application

  1. After you create a new CLR Console Application, a program is created for you that simply writes "Hello World" to the console. The name for the source file will be the same as the name you chose for the project above. In this example, it is named MyExecRefsAssembly.cpp.

  2. To use the math routines that were created in the class library, you must reference it. To do this, select References… from the Project menu. On the Property Pages dialog box, expand the Common Properties node and select References, and then select the Add New Reference… button. For more information about the References… dialog, see Framework and References, Common Properties, <Projectname> Property Pages Dialog Box.

  3. The Add Reference dialog is displayed. This dialog lists all the libraries that you can reference. The .NET tab lists the libraries that are included with the .NET Framework. The COM tab lists all the COM components on your computer. The Project tab lists all the projects in the current solution and any libraries they contain. On the Projects tab, select MathFuncsAssembly and then click OK. For more information about the Add Reference dialog, see Add Reference Dialog Box.

    Note

    You can reference an assembly directly from the source file by including the #using directive, as in #using <MathFuncsAssembly.dll>. For more information about this directive, see The #using Directive.

  4. You can now use the MyMathFuncs class in this application. In MyExecRefsAssembly.cpp, replace the contents of the file function with the following code:

    // MyExecRefsAssembly.cpp
    // compile with: /clr /FUMathFuncsAssembly.dll
    
    using namespace System;
    
    int main(array<System::String ^> ^args)
    {
        double a = 7.4;
        int b = 99;
    
        Console::WriteLine("a + b = {0}",
            MathFuncs::MyMathFuncs::Add(a, b));
        Console::WriteLine("a - b = {0}",
            MathFuncs::MyMathFuncs::Subtract(a, b));
        Console::WriteLine("a * b = {0}",
            MathFuncs::MyMathFuncs::Multiply(a, b));
        Console::WriteLine("a / b = {0}",
            MathFuncs::MyMathFuncs::Divide(a, b));
    
        return 0;
    }
    
  5. Build the executable by selecting Build Solution from the Build menu.

To run the application

  1. Make sure MyExecRefsAssembly is selected as the default project. From the Solution Explorer, select MyExecRefsAssembly, and then select Set As StartUp Project from the Project menu.

  2. To run the project, select Start Without Debugging from the Debug menu. The output should look like this:

    a + b = 106.4
    a - b = -91.6
    a * b = 732.6
    a / b = 0.0747474747474748
    

Next Steps

Previous:Creating and Using a Static Library (C+) | Next:Where to Go Next (C+)

See Also

Tasks

Visual C++ Guided Tour

Other Resources

Assemblies in the Common Language Runtime

Application Domains