在C#中调用DLL(动态链接库)通常涉及以下几种方法:使用DllImport属性进行P/Invoke(平台调用)、使用COM互操作,或者通过C++/CLI(如果你在使用.NETFramework并且愿意编写一些C++代码)进行封装。以下是每种方法的基本步骤:
1.使用DllImport进行P/Invoke
这是最常见且最简单的方法,用于调用非托管DLL中的函数。
2. 添加DllImport属性:在你的C#类中,使用DllImport属性声明一个静态外部方法。你需要指定DLL的名称和要调用的函数名。
【csharp】
using System;
using System.Runtime.InteropServices;
class Program
{
// 指定DLL名称和函数名
[DllImport("YourLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int YourFunction(int param1, string param2);
static void Main()
{
int result = YourFunction(42, "Hello");
Console.WriteLine(result);
}
}
3. 确保DLL在路径中:将DL