参考博客:
1. C#与C/C++的交互
2.C#使用CLR/C++的DLL间接调用Native C++的DLL
第一步,创建一个工程,选择C# -> Console Application。
第二步,在第一步创建的工程ConsoleApplication1里,添加子工程。右键'Solution ConsoleApplication1' -> Add -> New Project。选择C++ --> CLR --> Class Library,如下所示:
第三步,创建底层C++逻辑层。同上,这里选择C++ --> Win32 --> Win32 Project,确定后点Next,设置如下:
添加完三个工程之后,下面开始设置环境。
第四步,打开CPP工程里的CPP.h,添加一个比较两个int数的函数getBigger,如下。
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the CPP_EXPORTS
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// CPP_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef CPP_EXPORTS
#define CPP_API __declspec(dllexport)
#else
#define CPP_API __declspec(dllimport)
#endif
// This class is exported from the CPP.dll
class CPP_API CCPP {
public:
CCPP(void);
// TODO: add your methods here.
int getBigger(int x,int y)
{
return x>y?x:y;
}
};
extern CPP_API int nCPP;
CPP_API int fnCPP(void);
第六步,打开CLR工程的"CLR.h",加入 #include "CPP.h",如下:
// CLR.h
#include "CPP.h"
#pragma once
using namespace System;
namespace CLR {
public ref class Class1
{
// TODO: Add your methods for this class here.
public:
int getBigger_CLR(int x,int y)
{
CCPP c;
return c.getBigger(x,y);
}
};
}
右键ConsoleApplication1 --> Properties --> build event --> post build event command line
添加这段话:copy "$(SolutionDir)Debug\CPP.dll" "$(TargetDir)"
功能是自动把CPP产生的DLL复制到C#工程的bin\Debug下
第八步,也是最后一步,打开ConsoleApplication1工程里的program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CLR.Class1 c1 = new CLR.Class1();
Console.WriteLine(" 4 7 = " + c1.getBigger_CLR(4, 7).ToString());
Console.Read();
}
}
}