一. 准备
1. 开发环境:win 7 VS2010
2. 创建工程1) 创建一个C#的Console Application工程,文件-->新建-->项目-->其他语言->Visual C#-->控制台应用程序-->命名“ConsoleApplication1”。
2) 创建一个CLR/C++的工程,文件-->新建-->项目-->Visual C++-->CLR-->类库-->命名“NetCpp”。
3) 创建一个Native C++工程,文件-->新建-->项目-->Visual C++-->Win32 -->Win32 控制台应用程序-->命名“NativeCpp”-->Next-->选择"DLL"-->Export symbols.
二. 编码:
1. 打开"NativeCpp.h"在其中加入一些成员函数与变量;
<span style="font-size:18px;">#define NATIVECPP_API __declspec(dllexport)
// This class is exported from the NativeCpp.dll
class NATIVECPP_API CNativeCpp
{
public:
CNativeCpp(void);
// TODO: add your methods here.
int getA()
{
return 20;
}
};</span>
2. 在NetCpp工程中引用NativeCpp的DLL;
3. 打开CLR/C++工程的"NetCpp.h",加入#include "NativeCpp.h"
<span style="font-size:18px;">#include "NativeCpp.h"
using namespace System;
namespace NetCpp
{
public ref class Class1
{
public:
int getB()
{
CNativeCpp a;
return a.getA();
}
};
}</span>
4. 右击ConsoleApplication1工程的References-->Add Reference-->Projects-->选择"NetCpp"再把Native C++产生的DLL复制到C#工程的bin\\Debug\\目录下.
(
若想在修改了NativeC++代码后动态的更新Native C++的DLL,
需要在C#工程的属性中设置:PropertiesàBuild EventsàPost-build event command line:写入命令:
copy $(SolutionDir)Debug\NativeCpp.dll $(TargetDir)
)
5. 打开ConsoleApplication1工程program.cs
<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NetCpp.Class1 cl = new NetCpp.Class1();
Console.WriteLine("getA()" + c1.getB().ToString());
Console.Read();
}
}
}</span>