利用C++创建DLL并C#调用

日期:2018年11月26日

环境:window 10,VS2015 community

一、利用C++创建DLL

  1.新建项目;

  

  

  2.打开CreateDLL.cpp文件,并输入测试代码

  

 1 #include "stdafx.h"
 2 
 3 int __stdcall Add(int a, int b)
 4 {
 5     return a + b;
 6 }
 7 
 8 int __stdcall Sub(int a, int b)
 9 {
10     return a - b;
11 }
DLL Test Code

  3.给工程添加一个.def文件,并在该文件中插入以下代码;

1 LIBRARY CreateDLL
2 EXPORTS
3 Add @1,
4 Sub @2,
def Code

  注意这里的CreateDLL是工程名如果不同则应用程序连接库时会发生连接错误!

  其中LIBRARY语句说明该def文件是属于相应DLL的,EXPORTS语句下列出要导出的函数名称。我们可以在.def文件中的导出函数后加 @n,如Add@1,Sub@2,表示要导出的函数顺序号,在进行显式连时可以用到它。该DLL编译成功后,打开工程中的Debug目录,同样也会看到 CreateDLL.dll和CreateDLL.lib文件。

二、使用C#调用DLL

  1.在新建的C#工程中插入以下代码;

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Runtime.InteropServices;
 7 
 8 namespace AcmeCollections
 9 {
10     class Program
11     {
12         [DllImport(@"C:\Users\xxxxx\Desktop\study\CreateDLL\Debug\CreateDLL.dll")]//DLL的位置
13         public static extern int Add(int a, int b);
14 
15         [DllImport(@"C:\Users\xxxxx\Desktop\study\CreateDLL\Debug\CreateDLL.dll")]
16         public static extern int Sub(int a, int b);
17         static void Main(string[] args)
18         {
19             long ans;
20             string str;
21             
22             ans = Add(9, 7);
23             str = Convert.ToString(ans);
24             Console.WriteLine(str);
25             ans = Sub(9, 7);
26             str = Convert.ToString(ans);
27             Console.WriteLine(str);
28             Console.ReadLine();
29         }
30     }
C# Main Code

  2.运行结果;

  

 

参考链接:http://www.cnblogs.com/daocaoren/archive/2012/05/30/2526495.html

posted @ 2018-11-26 10:13  取名字脑壳疼  阅读(1957)  评论(0编辑  收藏  举报