How to use dll Library in a .NET Maui Windows project

qiang zhang 0 Reputation points
2023-11-09T09:27:04.36+00:00

How to use Native dll Library in a .NET Maui Windows project

Developer technologies | .NET | .NET MAUI
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-11-10T08:10:21.8366667+00:00

    Hello,

    Before the start, please ensure that the DLL is compatible with the target platform of your .NET MAUI application. If the DLL is platform-specific, ensure that it includes versions for the platforms you are targeting Windows.

    You can copy your DLL file to your MAUI application, I copy this DLL to the MauiProgram.cs level, And I set the property of Copy to Output Directory to the Copy always.

    For example, I have a DLL called MathLibrary.dll from this document walkthrough creating and using a dynamic link library cpp.

    If you want to use fibonacci_init and fibonacci_next method in the DLL. You can use the DllImport attribute to claim, we will call functions from a DLL

      [ComVisible(true)]
      [DllImport("MathLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
      public static extern int fibonacci_init(long arg1, long arg2);
    
    
     [ComVisible(true)]
      [DllImport("MathLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
      public static extern bool fibonacci_next();
    

    As note:

    DllImport Attribute: The [DllImport] attribute is used to specify the name of the DLL and the calling convention. The CallingConvention is essential to match the calling convention used by the native code. In this case, CallingConvention.Cdecl is specified.

    Function Signature: The extern keyword is used to declare an external function, and its signature should match the function in the DLL.

    In the end, we can call these functions.

    public MainPage()
    {
         InitializeComponent();
    
    
        fibonacci_init(123,4556);
        var res= fibonacci_next();
    }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.