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.