程序集(Assembly)一般是一个dll或exe文件,作为基于.net的文件格式与传统的非.net的dll和exe文件的区别是文件不仅包含了win32头,还包括一个clr头及元数据信息.程序集一般是单文件的(源文件),也可以是多文件.
一、vb.net与c#组成的多文件程序集
vb.net源文件 VBNet.vb:
Imports System
Namespace AssemblyTest
Public Class VBNet
Public Sub showText()
Console.WriteLine("AssemblyTest.VBNet")
End Sub
End Class
End Namespace
c#源文件 CSharp.cs:
using System;
namespace AssemblyTest
{
public class CSharp
{
public void showText()
{
System.Console.WriteLine("Assembly.CSharp");
}
}
}
测试文件 test.cs:
using System;
using AssemblyTest;
namespace Test
{
public class MyTest
{
public static void Main(System.String[] args)
{
VBNet vb=new VBNet();
CSharp cs=new CSharp();
vb.showText();
cs.showText();
}
}
}
1.分别编译两个源文件为模块:
vbc /t:module VBNet.vb
csc /t:module CSharp.cs
生成VBNet.netmodule和CSharp.netmodule
2.用程序集连接器al.exe将两个代码模块连接成程序集
al /t:library /out:private.dll VBNet.netmodule CSharp.netmodule
生成 private.dll
3.编译生成测试程序:
csc /r:private.dll test.cs
测试程序创建源程序VBNet.vb和CSharp.cs中的类,并调用类中的方法。
测试:
test.exe
输出:
AssemblyTest.VBNet
AssemblyTest.CSharp
二、c#与c++组成多文件程序集
c++是.net平台语言中比较特殊的一个,要想让c++生成程序集必须加上托管选项。另外为了让程序最终运行在clr堆栈上上,必须在定义类时加上ref修饰符,即声明为托管类。
源文件清单:cpp.cpp cs.cs test.cs
cpp.cpp:
#include <iostream>
using namespace std;
namespace MyAssembly
{
public ref class cppfile{
public:
void showText()
{
cout<<"cppfile::showText "<<endl;
}
};
}
cs.cs:
using System;
namespace MyAssembly
{
public class csharp
{
public void showText(int i)
{
System.Console.WriteLine("MyAssembly.scharp.showText"+i);
}
}
}
test.cs:
using System;
using MyAssembly;
namespace Test
{
class MyTest
{
public static void Main(System.String[] args)
{
csharp cs=new csharp();
cs.showText(2);
MyAssembly.cppfile cpp=new cppfile();
cpp.showText();
}
}
}
编译c#为代码模块: csc /t:module cs.cs 生成 cs.netmodule
编译c++为代码模块:cl /LN /clr:safe cpp.cpp 生成纯CIL模块cpp.netmodule cpp.obj
但是这一步编译出错了,所以需要先用/clr生成托管类,在连接成托管程序集。步骤如下:
cl /LN /clr cpp.cpp
al /t:library /out:private.dll cpp.netmodule cs.netmodule /platform:x86
csc /t:module /r:private.dll test.cs
link cpp.obj test.netmodule /LTCG /Subsystem:Console /entry:Test.MyTest.Main /out:test.exe
最后生成test.exe
运行结果:
MyAssembly.scharp.showText2
cppfile::showText
三、生成共享程序集
前面生成的都是私有程序集,当外部程序集要引用时必须在自己所在目录或子目录建立所引用程序集的拷贝。共享程序集是全局的,可以同时被多个程序集同时引用而不需要为每一个引用建立拷贝。要生成共享程序集必须为程序集添加数字签字。具体过程如下:
生成强命名文件 sn /k key.snk
然后以(一)中vb.net和c#的程序集为例 al /out:share.dll /t:library /keyf:key.snk VBNet.netmodule CSharp.netmodule /plarform:x86
这样就生成了多文件共享程序集share.dll。
如果需要在几个应用程序间共享程序集,可将其安装到全局程序集缓存中。安装了公共语言运行库的每台计算机均具有此计算机范围的代码缓存。全局程序集缓存中存储了专门指定给由计算机中若干应用程序共享的程序集。要安装到全局程序集缓存中,程序集必须具有强名称。全局程序集缓存的位置时%windows%assembly。