1 新建C++ dll项目
#pragma once
class COperation
{
public:
int Add(int a, int b);
int Avg(int* buf, int count);
};
#include "pch.h"
#include "COperation.h"
int COperation::Add(int a, int b)
{
return a+b;
}
int COperation::Avg(int* buf, int count)
{
int sum = 0;
for (size_t i = 0; i < count; i++)
{
sum += buf[i];
}
return sum/count;
}
2 建一个COperationInterface类
#pragma once
namespace OperationInterface
{
extern "C" __declspec(dllexport) int __stdcall Add(int a, int b);
extern "C" __declspec(dllexport) int __stdcall Avg(int* buf, int count);
}
#include "pch.h"
#include "COperationInterface.h"
#include "COperation.h"
COperation op;
int __stdcall OperationInterface::Add(int a, int b)
{
return op.Add(a,b);
}
int __stdcall OperationInterface::Avg(int* buf, int count)
{
return op.Avg(buf,count);
}
3 生成dll,lib
4 新建C#控制台项目TestDLL,将上面生成的dll拷贝到项目debug目录下,修改程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace TestDLL
{
class Program
{
[DllImport("DLL.dll")]
public extern static int Add(int a, int b);
[DllImport("DLL.dll")]
public extern static int Avg(int[] buf, int count);
static void Main(string[] args)
{
int res = Add(2, 3);
int[] buf = { 1, 2, 3, 4, 5 };
res = Avg(buf, 5);
}
}
}
运行即可
|