调用DLL函数的步骤是:
1、创建DLL;
2、在需要引用DLL的地方进行函数声明,例如:
using System;
using System.Runtime.InteropServices; //DllImport所在的命名空间
class DllImportTest
{
[DllImport("hashMain.dll")]
public static extern void hashMain();
[DllImport("hashMain.dll")]
private static extern void setMainUrl(string urlSeed);
[DllImport("hashMain.dll")]
public static extern bool checkWebInside(string url);
}
这里在DllImportTest类中声明了三个方法,第二个方法声明为私有的。这些方法就可以像在DllImportTest类中创建的方法一样使用了,只是它的方法体是在DLL中实现的。extern关键字声明该方法是个外部方法。
3、调用函数,例如:
namespace TestApplication
{
class Program
{
static void Main(string[] args)
{
bool result = DllImportTest.checkWebInside("http://www.baidu.com");
}
}
}
由于外部调用的方法必须声明为static的,因此只能通过类进行引用。在方法的使用上,跟一般的类得静态方法没有什么区别。
4、需要注意的问题:被调用的DLL必须放在Program所在的项目集的Debug文件夹下,而不是放在DllImportTest所在项目集的Debug文件夹下。因为在系统只会在运行exe文件的那个目录下寻找DLL,而运行的exe文件是在运行的那个项目集的Debug目录下。也可以将DLL放在windows/system32目录下,或者加入到系统环境变量的path下。