C#使用CLR/C++的DLL间接调用Native C++的DLL

3 篇文章 1 订阅

一. 准备

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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值