您的位置:首页 > 编程语言 > C语言/C++

.dll文件讲解,及其调用

2017-12-04 10:27 295 查看
.dll文件我目前遇到了三类,切这两类代表的意义完全不同。

一种是在c++下面,.dll文件里面是相当于机器码,叫做动态链接库,其连接方式有静态连接与动态连接。

下面是静态连接

//静态连接用到
#include "stdafx.h"

//关键在于加入这一句,意为将C语言下的程序导出为DLL

extern "C"_declspec(dllexport) void maopao(int *p,int count);

void maopao(int *p,int count)

{

int temp=0;

for(int i=1;i<count;i++)

{

for(int j=count-1;j>=i;j--)

{

if(p[j]>p[j-1])

{

temp=p[j];

p[j]=p[j-1];

p[j-1]=temp;

}

}

}

}

//调用
#include<iostream>

#include<time.h>

using namespace std;

//将export改为import即导出变导入即可

extern "C"_declspec(dllimport) void maopao(int *p,int count);

int main()

{

int a[10];

srand(time(0));

for(int i=0;i<10;i++)

a[i]=rand()%50;

maopao(a,10);

for(int i=0;i<10;i++)

cout<<a[i]<<endl;

getchar();//为方便调试

return 0;

}


下面是动态连接,到处方法是一样的

#include "stdafx.h"

//关键在于加入这一句,意为将C语言下的程序导出为DLL

extern "C"_declspec(dllexport) void maopao(int *p,int count);

void maopao(int *p,int count)

{

int temp=0;

for(int i=1;i<count;i++)

{

for(int j=count-1;j>=i;j--)

{

if(p[j]>p[j-1])

{

temp=p[j];

p[j]=p[j-1];

p[j-1]=temp;

}

}

}

}

#include<iostream>
#include<Windows.h>
#include<time.h>
typedef int(*Dllfun)(int *,int);
using namespace std;
int main()
{
Dllfun maopao1;
HINSTANCE hdll;
hdll=LoadLibrary("D:\\net源码\\maopaoa_dll\\Debug\\maopaoa_dll.dll");
if(hdll==NULL)
{FreeLibrary(hdll);
}
maopao1=(Dllfun)GetProcAddress(hdll,"maopao");
if(maopao1==NULL)
{FreeLibrary(hdll);
}
int a[10];
srand(time(0));
for(int i=0;i<10;i++)
a[i]=rand()%50;
maopao1(a,10);
for(int i=0;i<10;i++)
cout<<a[i]<<endl;

FreeLibrary(hdll);

}


第二种 是.dll是 AXtivex控件 ,是一种微软的共用控件的封装,比如图表,频谱控件的封装,常用于c++中,其本身也是二进制文件。

连接方式 #connect(“…”)

第三种是在c#中,叫做程序集,其运行在.net框架上,其本身没有包含机器码,需要在由.net框架转化为机器码。 其调用方法主要包括两种途径。一种是程序集引用,在vs项目管理,一种是通过反射,反射代码如下

Assembly asm= Assembly.LoadFile("路径。。");
foreach (var type in asm.GetTypes())
{
//如果是ISay接口
if (type.GetInterfaces().Contains(typeof (ISay)))
{
//创建接口类型实例
var isay = Activator.CreateInstance(type) as ISay;
if (isay != null)
{
result.Add(isay);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 c# activex控件