1. Create a C++ Win32 Console Application
2. 在新建的工程中添加头文件CppDll.h,内容如下
#pragma once
#ifdef CPPDLL_EXPORTS
#define CPPDLL_EXPORTS __declspec(dllexport)
#else
#define CPPDLL_EXPORTS __declspec(dllimport)
#endif
CPPDLL_EXPORTS int Add(int a, int b);
3. 在工程中的CppDll.cpp文件中编辑,内容如下
// CppDll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "CppDll.h"
int Add(int a, int b)
{
return a + b;
}
4. 添加一个Module-Definition File(.def),内容如下
LIBRARY
EXPORTS
Add @1
5. 创建一个C# Console Application 工程
6. 编辑Program.cs,内容如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
[DllImport("CppDll.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Add")]
public static extern int Add(int a, int b);
static void Main(string[] args)
{
int a = 1;
int b = 2;
int c = Add(a,b);
Console.WriteLine("{0} + {1} = {2}", a, b, c);
Console.ReadKey();
}
}
}
7. 编译C++和C#的项目,注意C++项目编译生成的CppDll.dll文件要拷贝到C#目标文件夹,这样DllImport才能找到该Dll文件。然后就可以运行C#的ConsoleApplication1.exe了!