注意,在接下来的过程中,需要选择dll.点击完成创建工程。
工程创建完成后,里面会有很多文件,打开源文件目录下的 工程名.cpp文件(其他文件都不用管)
在此文件中编写代码如下:
#include "stdafx.h"
#include<iostream>
using namespace std;
extern "C" int _declspec(dllexport) add(int a ,int b)
{
return a+b;
}
注意上面用红体字标出的部分,这部分代码将告诉编译器此函数将作为导出函数。对于其他函数可以依此类推。点击编译按钮就编译出了dll文件。另外要说明的是,这是一种比较简单的生成dll文件的方法,不用导出函数的名称及其入口点。
至此,dll文件就已经生成了。
我们可以再任何语言中测试此dll文件。以下仅提供C++和C#语言中调用DLL中函数的方法。
在C++中,我们可以用如下方法调用DLL文件中的函数。
#include<windows.h>
#include<stdio.h>
#include<iostream>
using namespace std;
typedef int(__stdcall *fun)(int,int);//声明函数指针
int main()
{
HINSTANCE handle = LoadLibraryA("test.dll");//加载dll文件
fun add=NULL;
add=(fun)GetProcAddress(handle,"add");//导出函数
int a,b;
cin>>a>>b;
cout<<add(a,b)<<endl;
system("pause");
return 0;
}
在C#中,调用DLL文件中的函数同样很简单。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace TEST_DLL
{
class Program
{
[DllImport("test.dll", EntryPoint = "add")]
public static extern int add(int a,int b);
static void Main(string[] args)
{
int a = 108, b = 109;
int c = add(a, b);
Console.WriteLine(c);
Console.Read();
}
}
}
注意,以上在加载dll文件的时候,按照我的写法,dll文件必须和可执行程序在同一目录下,否则会出现找不到dll文件的运行错误。当然,也可以应用dll文件的绝对路径。另外对于user32.dll等系统常用的dll文件,即使没有放到可执行程序的相同路径下,也没有引用其绝对路径,编译器也是能够找到此文件的。