c#调用DLL

1.创建DLL

文件->新建-》项目-》visual c#-》windows桌面-》类库,名称起一个,如DllTest

编写代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DllTest
{
    public class Class1
    {
        public void ShowMessage()
        {
            Console.WriteLine("你以成功调用了动态连接!");
            Console.ReadLine();
        }
    }
}

2.检查输出

在解决方案上右击——属性,在应用程序选卡中需要注意一下三个内容。
1.程序集名称2.默认命名空间3.输出类型
1.DllTest      2.DllTest           3.类库


3.生成DLL

生成-》生成DllTest

生成成功后可以在目录下能看到生成的Dll


4.调用DLL

新建一个控制台应用程序,来实现该dll的调用。例如新建一个DLLExample。

解决方案管理器选中,右键添加-》引用-》浏览,选择DllTest.dll,确定。
编辑代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//下面两项必须添加
using System.Runtime.InteropServices;
using DllTest;
namespace DLLExample
{
    class Program
    {
        [DllImport("DllTest.dll")]
        public static extern void ShowMessage();
        static void Main(string[] args)
        {
            //实例化
            DllTest.Class1 i = new Class1();
            //调用动态链接库的方法
            i.ShowMessage();
        }
    }
}

运行即可成功

版权声明:

原文地址:https://www.cnblogs.com/walccott/p/4957066.html