#pragma once
#include <string>
public ref class Function
{
public:
Function(void);
~Function(void);
int menber;
int menberFuncAdd(int a,int b);
System::String^ say(System::String^ str);
};
int Function::menberFuncAdd(int a,int b)
{
return a+b;
}
System::String^ Function::say(System::String^ str)
{
return str;
}
填写完后Function.h文件会报错,错误类型如下:
这里需要在C++项目里面设置,让动态库受到公共语言运行时的支持。如下图所示:
打开项目属性
修改完成后点击项目右键生成DLL,看是否报错,成功结果如下图:
3、添加测试程序:
在该解决方案中添加测试程序:
添加一个C#控制台测试程序:
添加完后设为启动项:
添加引用:
将C++项目添加到C#的项目中:
4、编写测试代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Function fun = new Function();
Console.WriteLine(fun.menberFuncAdd(1, 2));
Console.WriteLine(fun.say("Hello World"));
Console.ReadKey();
}
}
}
#include "..\SampleCppClass\SampleCppClass.h"
namespace SampleCppWrapper
{
extern "C" __declspec(dllexport) int __stdcall Add(int n1, int n2);
extern "C" __declspec(dllexport) int __stdcall Sub(int n1, int n2);
}
//SampleCppWrapper.cpp
#include "SampleCppWrapper.h"
namespace SampleCppWrapper
{
SampleCppClass* g_pObj = new SampleCppClass();
int __stdcall Add(int n1, int n2)
{
return g_pObj->Add(n1, n2);
}
int __stdcall Sub(int n1, int n2)
{
return g_pObj->Sub(n1, n2);
}
}
在C#中,再调用SampleCppWrapper.dll中的公共方法:
[DllImport("SampleCppWrapper.dll")]
private static extern int Add(int n1, int n2);
[DllImport("SampleCppWrapper.dll")]
private static extern int Sub(int n1, int n2);
3、 使用C++类库中的回调函数
C++的回调函数是一种事件响应机制,和C#的委托相似,比如一个C++类中的回调函数:
// SampleCppClass.h
#pragma once
typedef void (*LoopCallback)(void* pContext);
class __declspec(dllexport) SampleCppClass
{
public:
SampleCppClass(void);
~SampleCppClass(void);
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SampleCsTest
{
public partial class Form1 : Form
{
[StructLayout(LayoutKind.Sequential)]
private class Context
{
public Form1 Form { get; set; }
}