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

时间:2023-03-09 13:17:58
利用C++创建DLL并C#调用

日期:2018年11月26日

环境:window 10,VS2015 community

一、利用C++创建DLL

  1.新建项目;

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

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

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

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

 #include "stdafx.h"

 int __stdcall Add(int a, int b)
{
return a + b;
} int __stdcall Sub(int a, int b)
{
return a - b;
}

DLL Test Code

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

 LIBRARY CreateDLL
EXPORTS
Add @,
Sub @,

def Code

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

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

二、使用C#调用DLL

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

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices; namespace AcmeCollections
{
class Program
{
[DllImport(@"C:\Users\xxxxx\Desktop\study\CreateDLL\Debug\CreateDLL.dll")]//DLL的位置
public static extern int Add(int a, int b); [DllImport(@"C:\Users\xxxxx\Desktop\study\CreateDLL\Debug\CreateDLL.dll")]
public static extern int Sub(int a, int b);
static void Main(string[] args)
{
long ans;
string str; ans = Add(, );
str = Convert.ToString(ans);
Console.WriteLine(str);
ans = Sub(, );
str = Convert.ToString(ans);
Console.WriteLine(str);
Console.ReadLine();
}
}

C# Main Code

  2.运行结果;

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

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