2015.5.9 C#编写DLL及C#调用C#DLL

过程比C#调用VC++dll简单。

一、创建DLL

新建工程,类型选择类库,生成的结果就是dll

注意:在项目属性-应用程序中,注意三个地方,程序集名称和默认命名空间可以调整,但要一致,别的程序调用此DLL时,可通过using命名空间,而后类名+函数名调用。输出类型保持默认的“类库”不变。

此DLL中可以应用VC创建的DLL,但此时本DLL属性只能是X86.调用vc++dll方法还是用

[DllImport("space.dll")]

public static extern void CalcCording(double jin, double wei, double ang, double r, out double ojin, out double owei);

dll中可以进行执行、删除文件等操作。

此外dll中要获得本dll本地路径就不能用Application.ExecutablePath()函数了额,而要用自定义的

private static string GetAssemblyPath()

{

string _CodeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

_CodeBase = _CodeBase.Substring(8, _CodeBase.Length - 8);    // 8是 file:// 的长度

string[] arrSection = _CodeBase.Split(new char[] { '/' });

string _FolderPath = "";

for (int i = 0; i < arrSection.Length - 1; i++)

_FolderPath += arrSection[i] + "/";

_FolderPath = _FolderPath.Replace("/", "\\");

return _FolderPath;

}

二、C#调用C#dll

1、可在dll项目同一解决方案下添加WindowsForm项目,并设为启动项目

2、以添加引用的方式将上面创建的dll引入本项目

3、直接用dll的类名+函数名的方法调用dll中的函数(需要using命名空间),不用[DllImport("...")]的方法引用了。

4、参数传递更加自由,可用数组或List<>类型传递参数。

posted on 2016-10-15 17:29  mol1995  阅读(804)  评论(0编辑  收藏  举报

导航