SoFunction
Updated on 2025-03-03

Examples of several methods of using Dll in C#

1. What is DLL

A dynamic link library (DLL) is a file containing code and data that can be used simultaneously by multiple programs. It is loaded into memory on demand during program runs, meaning they can be dynamically linked and called dynamically. This mechanism not only saves memory, but also promotes code reuse and version control.

2. Motivation to use DLLs in C#

The motivation for using DLL mainly includes the following aspects:

  • Code reuse: Encapsulate common functions into DLLs for use in multiple projects.
  • Reduce application size: Instead of including all code in each application, all the code is referenced.
  • Modular development: Making complex software systems easier to manage and maintain.
  • Cross-language call: Call a function from unmanaged code (such as C/C++).

3. Reference DLLs through Visual Studio

Referring to a DLL in Visual Studio is the easiest way to use a managed assembly.

Create and reference DLLs

  • Create a DLL project

    • Open Visual Studio and create a new C# class library project.

    • Write your functional code, such as the following simple math library:

namespace MathLibrary
{
    public class Calculator
    {
        public int Add(int a, int b)
        {
            return a + b;
        }

        public int Subtract(int a, int b)
        {
            return a - b;
        }
    }
}
  • Compile and generate DLLs. In Solution Explorer, right-click the project and select the Build option.

  • Reference the DLL in other projects

    • Right-click "Reference" in the project that needs to use the DLL and select "Add Reference".
    • Under the Browse tab, locate the generated DLL file and add it.
  • Use classes in DLL

using MathLibrary;

class Program
{
    static void Main()
    {
        Calculator calc = new Calculator();
        ($"Add: {(10, 5)}");
        ($"Subtract: {(10, 5)}");
    }
}

4. Call unmanaged code using P/Invoke

Platform Invocation Services (P/Invoke) provides a way to call unmanaged code (such as C/C++) from C#. This feature is especially useful for using the operating system-provided API or legacy C/C++ libraries.

Example: Calling the Windows API

Suppose we need to call the Windows APIMessageBoxFunction.

  1. Declare functions

using System;
using ;

class Program
{
    [DllImport("", CharSet = )]
    public static extern int MessageBox(IntPtr hWnd, string text, string caption, int options);

    static void Main()
    {
        MessageBox(, "Hello, World!", "My Box", 0);
    }
}
  • Key points analysis

    • useDllImportThe property indicates that this is a function called from an unmanaged DLL.
    • CharSetSet toUnicodeTo process character encoding.

5. Use COM objects

Using COM objects in C# needs to be implemented through a runtime callable wrapper (RCW). Visual Studio can automatically generate RCWs.

Example: Using Microsoft Excel COM Objects

  • Add a reference

    • Select "Add Reference" in the project and find the "COM" tab.
    • Add "Microsoft Excel 16.0 Object Library".
  • Using Excel COM Objects

using Excel = ;

class Program
{
    static void Main()
    {
         xlApp = new ();
         = true;

         workbook = ();
         worksheet = ()[1];
        [1, 1] = "Hello, Excel!";

        ("");
        ();
        ();
    }
}
  • Things to note

    • After using the COM object, you need to callQuit()Method and release the object. This can be passedto achieve to avoid memory leakage.

6. Loading DLLs with reflection

Reflection provides the ability to load and use assembly dynamically at runtime. This is especially useful for scenarios where objects or methods are created when the program is executed.

Example: Dynamic loading of DLLs

  • Dynamic loading and calling methods

using System;
using ;

class Program
{
    static void Main()
    {
        // Load DLL        Assembly assembly = ("");

        // Get Calculator type        Type calculatorType = ("");

        // Create Calculator instance        object calculatorInstance = (calculatorType);

        // Get Add method        MethodInfo addMethod = ("Add");

        // Call the Add method        object result = (calculatorInstance, new object[] { 10, 5 });

        ($"Result of Add: {result}");
    }
}
  • Pros and cons of reflection

    • advantage: Flexible, you can decide which piece of code to load and call at runtime.
    • shortcoming: Performance overhead is high and may cause runtime errors when the code structure changes.

7. Practical examples and code analysis

Let's organize the steps to load DLLs using different ways through an actual project. Suppose we want to develop an image processor whose core functionality is implemented by a complex C++ library, which we want to call in C#.

C++ DLL creation

Here is a simple C++ dynamic link library example that provides the ability to convert image to grayscale:

// 
#include ""

extern "C" __declspec(dllexport) void ToGrayscale(unsigned char* image, int width, int height)
{
    for (int i = 0; i < width * height * 3; i += 3)
    {
        unsigned char gray = (unsigned char)(0.299 * image[i] + 0.587 * image[i + 1] + 0.114 * image[i + 2]);
        image[i] = image[i + 1] = image[i + 2] = gray;
    }
}

C# call P/Invoke

Call the above C++ function in a C# program:

using System;
using ;
using ;
using ;
using ;

class Program
{
    [DllImport("", CallingConvention = )]
    public static extern void ToGrayscale(byte[] image, int width, int height);

    static void Main()
    {
        string inputImagePath = "";
        string outputImagePath = "";

        Bitmap bitmap = new Bitmap(inputImagePath);
        Rectangle rect = new Rectangle(0, 0, , );
        BitmapData bmpData = (rect, , );

        int bytes = () * ;
        byte[] rgbValues = new byte[bytes];
        IntPtr ptr = bmpData.Scan0;

        (ptr, rgbValues, 0, bytes);

        ToGrayscale(rgbValues, , );

        (rgbValues, 0, ptr, bytes);
        (bmpData);
        (outputImagePath);

        ("Image converted to grayscale and saved as " + outputImagePath);
    }
}

8. FAQs and Solutions

  • Unable to load DLL

    • Make sure that the DLL file is in the application's running directory.
    • Check that the DLL's dependencies are installed correctly.
  • Failed to call the function

    • Check the consistency of P/Invoke declaration and actual DLL function signature.
    • Make sure that the conversion between data types is correct, such asintstringMapping to unmanaged types.
  • Memory leak

    • Make sure that all unmanaged resources are released correctly, especially when handling COM objects.

9. Performance optimization and precautions

  • Reduce unnecessary calls: Frequent DLL calls may cause performance problems, and data should be processed in batches as much as possible.
  • Try to use managed code: For simple features, priority is given to the use of C# implementation to avoid unnecessary complexity and errors.
  • Cache method information: When using reflection, cache the methods and attribute information that need to be called to reduce performance overhead.

10. Summary

C# Using DLL provides flexible ways to reuse code and extend functionality. From directly referencing managed assemblies, to calling unmanaged code through P/Invoke, to loading DLLs with COM objects and reflections, each approach has its own unique application scenarios and challenges. In actual development, choosing the right technology requires comprehensive consideration of the project's characteristics, performance requirements and maintenance costs. By deeply understanding the methods and precautions for implementing these technologies, it is possible to better use DLLs in C# projects to implement complex functions.

print("Embrading new technologies is the king!")

The above is the detailed content of several examples of C# using Dll. For more information about C# using Dll, please pay attention to my other related articles!