首页 / 软件开发 / C# / C#托管代码与C++非托管代码互相调用一(C#调用C++代码&.net 代码安全)
C#托管代码与C++非托管代码互相调用一(C#调用C++代码&.net 代码安全)2011-10-17 博客园 Jianchidaodi在最近的项目中,牵涉到项目源代码保密问题,由于代码是C#写的,容易被反编译,因此决定抽取核 心算法部分使用C++编写,C++到目前为止好像还不能被很好的反编译,当然如果你是反汇编高手的话,也 许还是有可能反编译。这样一来,就涉及C#托管代码与C++非托管代码互相调用,于是调查了一些资料, 顺便与大家分享一下一. C# 中静态调用C++动态链接1. 建立VC工程CppDemo,建立的时候选择Win32 Console(dll),选择Dll。2. 在DllDemo.cpp文件中添加这些代码。extern "C" __declspec(dllexport) int Add(int a,int b)
{
return a+b;
}
3. 编译工程。4. 建立新的C#工程,选择Console应用程序,建立测试程序InteropDemo5. 在Program.cs中添加引用:using System.Runtime.InteropServices;6. 在pulic class Program添加如下代码: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)
{
Console.WriteLine(Add(1, 2));
Console.Read();
}
}
}
好了,现在您可以测试Add程序了,是不是可以在C# 中调用C++动态链接了,当然这是静态调用,需要 将CppDemo编译生成的Dll放在DllDemo程序的Bin目录下