1. C++ win32项目 dll 空项目
添加CPPDemo.cpp
<span style="white-space:pre"> </span>extern "C" __declspec(dllexport) int Add(int x, int y)
<span style="white-space:pre"> </span> {
<span style="white-space:pre"> </span> return x + y;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span> extern "C" __declspec(dllexport) int Sub(int x, int y)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span> return x - y;
<span style="white-space:pre"> </span> }
<span style="white-space:pre"> </span> extern "C" __declspec(dllexport) int Multiply(int x, int y)
<span style="white-space:pre"> </span> {
<span style="white-space:pre"> </span> return x * y;
<span style="white-space:pre"> </span> }
<span style="white-space:pre"> </span> extern "C" __declspec(dllexport) int Divide(int x, int y)
<span style="white-space:pre"> </span> {
<span style="white-space:pre"> </span> return x / y;
<span style="white-space:pre"> </span> }
生成.dll和.lib
2. C# 控制台应用程序 将.dll放在debug目录下
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"> 添加类</span><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">CPPDLL.cs</span>
<pre name="code" class="csharp"> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices; //添加
namespace ConsoleApplication1
{
class CPPDLL
{
[DllImport("cdll.dll", CallingConvention = CallingConvention.Cdecl)] //Cdecl很重要
public static extern int Add(int x, int y);
[DllImport("cdll.dll",CallingConvention = CallingConvention.Cdecl)]
public static extern int Sub(int x, int y);
[DllImport("cdll.dll",CallingConvention = CallingConvention.Cdecl)]
public static extern int Multiply(int x, int y);
[DllImport("cdll.dll",CallingConvention = CallingConvention.Cdecl)]
public static extern int Divide(int x, int y);
}
}
修改program.cs
static void Main(string[] args)
{
int result = CPPDLL.Add(10, 20);
Console.WriteLine("10 + 20 = {0}", result);
result = CPPDLL.Sub(30, 12);
Console.WriteLine("30 - 12 = {0}", result);
result = CPPDLL.Multiply(5, 4);
Console.WriteLine("5 * 4 = {0}", result);
result = CPPDLL.Divide(30, 5);
Console.WriteLine("30 / 5 = {0}", result);
}