Search code examples
c#dlldllimportdllexportdllregistration

C# Created DLL .NET 7, DllImport Don't work


I don't understand why this error in my screen):

enter image description here

EdiUseDLL:

using System;
using System.Runtime.InteropServices;

class Program
{
    const string Path = @"C:\Users\Maxim\Desktop\EdiUseDLL\EdiLibraryExample\bin\Release\net7.0\EdiLibraryExample.dll";
    [DllImport(Path, CallingConvention = CallingConvention.Cdecl)]
    public static extern int Add(int a, int b);

    static void Main()
    {
        int result = Add(5, 3);
        Console.WriteLine("Result of addition: " + result); 
    }
}

EdiLibraryExample:

namespace EdiLibraryExample
{
    public class Class1
    {
        public static int Add(int a, int b)
        {
            return a + b;
        }

    }
}

enter image description here

How to create dll which I can use with DLLImport in c#

I hope you will help me!)


Solution

  • There are two kinds of DLLs: managed and unmanaged.

    Managed refers to being managed by CLR. Typically DLLs compiled from C# are managed DLLs, which can be directly referenced by another C# project or dynamically loaded using methods such as Assembly.LoadFrom.

    Other DLLs are called unmanaged DLLs, which are usually compiled from other programming languages such as C++. Using such DLLs in C# projects requires attributes such as DllImportAttribute to load them.

    If a DLL is compiled from a C++/CLI project, it can contain both managed and unmanaged code.

    Bottom line: you cannot use Assembly.LoadFrom for unmanaged DLLs.