您的位置:首页 > 编程语言 > C语言/C++

C# 中静态调用C++dll 和C# 中动态调用C++dll

2012-10-24 11:09 411 查看
在最近的项目中,牵涉到项目源代码保密问题,由于代码是C#写的,容易被反编译,因此决定抽取核心算法部分使用C++编写,C++到目前为止好像还不能被很好的反编译,当然如果你是反汇编高手的话,也许还是有可能反编译。这样一来,就涉及C#托管代码与C++非托管代码互相调用,于是调查了一些资料,顺便与大家分享一下:

一. C# 中静态调用C++动态链接

1. 建立VC工程CppDemo,建立的时候选择Win32 Console(dll),选择Dll。

2. 在DllDemo.cpp文件中添加这些代码。

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace InteropDemo
{
class Program
{
//[DllImport("CppDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
//public static extern int Add(int a, int b); //DllImport请参照MSDN

static void Main(string[] args)
{
//1. 动态加载C++ Dll
int hModule = NativeMethod.LoadLibrary(@"c:\CppDemo.dll");
if (hModule == 0) return;

//2. 读取函数指针
IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");

//3. 将函数指针封装成委托
Add addFunction = (Add)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(Add));

//4. 测试
Console.WriteLine(addFunction(1, 2));
Console.Read();
}

/// <summary>
/// 函数指针
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
delegate int Add(int a, int b);

}
}


通过如上两个例子,我们可以在C#中动态或者静态的调用C++写的代码了.

转自:http://www.cnblogs.com/Jianchidaodi/archive/2009/03/09/1407270.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: