http://www.cnblogs.com/Jianchidaodi/archive/2009/03/11/1407270.html#1473515

http://www.cnblogs.com/Jianchidaodi/archive/2009/03/11/1408661.html

C#托管代码与C++非托管代码互相调用一(C#调用C++代码&.net 代码安全)

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

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

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

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

Code

extern "C" __declspec(dllexport) int Add(int a,int b)

{

   

     return a+b;

}

    3. 编译工程。

4. 建立新的C#工程,选择Console应用程序,建立测试程序InteropDemo

    5. 在Program.cs中添加引用:using System.Runtime.InteropServices;

6. 在pulic class Program添加如下代码:

Code

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目录下

二. C# 中动态调用C++动态链接

在第一节中,讲了静态调用C++动态链接,由于Dll路径的限制,使用的不是很方便,C#中我们经常通过配置动态的调用托管Dll,例如常用的一些设计模式:Abstract
Factory, Provider,
Strategy模式等等,那么是不是也可以这样动态调用C++动态链接呢?只要您还记得在C++中,通过LoadLibrary,
GetProcess,
FreeLibrary这几个函数是可以动态调用动态链接的(它们包含在kernel32.dll中),那么问题迎刃而解了,下面我们一步一步实验

1.  将kernel32中的几个方法封装成本地调用类NativeMethod

Code

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

namespace InteropDemo

{

    public static class NativeMethod

    {

        [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]

        public static extern int LoadLibrary(

            [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]

        public static extern IntPtr GetProcAddress(int hModule,

            [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]

        public static extern bool FreeLibrary(int hModule);

    }

}

2. 使用NativeMethod类动态读取C++Dll,获得函数指针,并且将指针封装成C#中的委托。原因很简单,C#中已经不能使用指针了,如下         

            int hModule = NativeMethod.LoadLibrary(@"c:"CppDemo.dll");

IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");

详细请参见代码

Code

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++写的代码了,找了半天好像没看到可以上传源代码的地方,不过代码比较清楚了,需要的朋友可以留个邮箱,源代码下载

C#托管代码与C++非托管代码互相调用二(C++调用C#代码)

上篇文章提到,目前项目想做到核心部分代码不被反编译,而考虑到团队成员都是比较熟悉C#,因此核心算法部分采用C++,而其他地方则采用C#(例如数据访问层,界面层都使用C#语言)。在上一篇文章中完成了C#托管代码调用C++非托管代码,现在接着完成第二部分,即C++非托管代码调用C#托管代码(源代码下载),分为两部分,首先C#建立COM+组件,其次是C++调用COM+组件。

C#建立COM+组件

1. 在VS中,新建类库ComInterop

2.  在类库新增接口:ComInteropInterface, 及相应的实现ComInterop, ComInterop同时必须继承自ServicedComponent。ComInteropInterface中有两个简单接口:

int Add(int a, int b);

int Minus(int a, int b);

具体代码如下:

Code

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;

using System.Runtime.InteropServices;

using System.EnterpriseServices;

namespace ComInteropDemo

{

    //接口声明

    [Guid("7103C10A-2072-49fc-AD61-475BEE1C5FBB")]  

    public interface ComInteropInterface

    {

        [DispId(1)]

        int Add(int a, int b);

[DispId(2)]

        int Minus(int a, int b);

    }

//对于实现类的声明

    [Guid("87796E96-EC28-4570-90C3-A395F4F4A7D6")]

    [ClassInterface(ClassInterfaceType.None)]

    public class ComInterop : ServicedComponent, ComInteropInterface

    {

        public ComInterop() { }

public int Add(int a, int b)

        {

            return a + b;

        }

public int Minus(int a, int b)

        {

            return a - b;

        }

    }

}

3 . 使用REGASM命令导出虚拟表,当重新编译生产Dll时需要使用REGASM  /u命令将前一次Dll注销

REGASM  ComInteropDemo.dll /tlb ComInteropDemo.tlb

REGASM  /u ComInteropDemo.dll

首先对COM+组件的写法需要注意以下几点:

1. 接口,事件,方法,属性必须是public

2.  方法和属性必须在接口中声明,事件也必须在事件接口中声明.

否则将在VC中无法调用,在接口中声明主要是为了在COM 中的vtab中.

3.  必须对接口中的方法,属性,事件前声明[DispId(1)]

4. 每个接口都必须有一个GUID

5.  而且项目一定需要是COM Interop,并且具有强命名

6.  组件ComVisible属性必须为true,这里强调的原因是VS中默认值为false

C++调用C# COM+组件

步骤:

1. 建立C++ 项目CppLoader,项目类型选择Win32,控制台应用程序

2.  在头文件中导入类型库tlb

#import "..\\Debug\\ComInteropDemo.tlb"

3. 初始化COM以及产生智能指针(一般是在需要调用COM组件中提供的方法时就需要产生指向该接口的智能指针)

4. 调用COM中的方法Add

5. 释放环境 ,具体代码如下

Code

#include "stdafx.h"

#include <iostream>

using namespace std;

#import "..\\Debug\\ComInteropDemo.tlb"

//路径一定要正确

int _tmain(int argc, _TCHAR* argv[])

{

    HRESULT hr;

//ComInteropDemo::ComInterop *p;

//初始化COM

    CoInitialize ( NULL );

//创建智能指针ComInteropDemo::ComInteropInterface

    ComInteropDemo::ComInteropInterfacePtr ptr;

//创建实例

    hr = ptr.CreateInstance(__uuidof (ComInteropDemo::ComInterop));

if(hr == S_OK)

    {

        cout << ptr->Add (1.0, 2.0);

    }

CoUninitialize ();

    return 0;

}

C#托管代码与C++非托管代码互相调用的更多相关文章

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

    在最近的项目中,牵涉到项目源代码保密问题,由于代码是C#写的,容易被反编译,因此决定抽取核心算法部分使用C++编写,C++到目前为止好像还不能被很好的反编译,当然如果你是反汇编高手的话,也许还是有可能 ...

  2. VC++ 非托管代码 & 托管代码

    #pragma managed #pragma unmanaged 看了好多好多非托管代码和托管代码之间相互调用,感觉都没有说在重点上,到底怎么用才是关键,理论的东西我们到微软官网上就可以找到,毕竟这 ...

  3. [转]C# 互操作性入门系列(四):在C# 中调用COM组件

    传送门 C#互操作系列文章: C# 互操作性入门系列(一):C#中互操作性介绍 C# 互操作性入门系列(二):使用平台调用调用Win32 函数 C# 互操作性入门系列(三):平台调用中的数据封送处理 ...

  4. FormatMessage与GetLastError配合使用,排查windows api调用过程中的错误

    前一段时间在学习windows api调用过程中,遇到过一些调用错误或者程序没能显示预期的结果,或者直接出现vc运行时错误. 这对新手来说是司空见惯的事,因为不太熟悉难免会出错,出错的信息如果能显示很 ...

  5. silverlight 进行本地串口调用的一种可行的解决方法

    silverlight 是一个很不错的开发平台,我们可以设计出很绚丽的界面,用户可以拥有很好的体验,但是就目前来说,进行本地串口的直接调用时不行的,因为安全的原因,有没有相对简单的调用方式呢? 答案是 ...

  6. C# 互操作性入门系列(二):使用平台调用调用Win32 函数

    好文章搬用工模式启动ing ..... { 文章中已经包含了原文链接 就不再次粘贴了 言明 改文章是一个系列,但只收录了2篇,原因是 够用了 } --------------------------- ...

  7. [转]C# 互操作性入门系列(二):使用平台调用调用Win32 函数

    传送门 C#互操作系列文章: C# 互操作性入门系列(一):C#中互操作性介绍 C# 互操作性入门系列(二):使用平台调用调用Win32 函数 C# 互操作性入门系列(三):平台调用中的数据封送处理 ...

  8. asp.net c# 网上搜集面试题目大全(附答案)

    1.String str=new String("a")和String str = "a"有什么区别? String str = "a"; ...

  9. C# 托管和非托管混合编程

    在非托管模块中实现你比较重要的算法,然后通过 CLR 的平台互操作,来使托管代码调用它,这样程序仍然能够正常工作,但对非托管的本地代码进行反编译,就很困难.   最直接的实现托管与非托管编程的方法就是 ...

随机推荐

  1. nfs文件系统启动参数配置

    1. tiny6410(增强版)bootargs(nfs文件挂载)启动参数(周学伟) noinitrd console=ttySAC0,115200 lcd=S70 init=/init root=/ ...

  2. URAL 1080 Map Coloring(染色)

    Map Coloring Time limit: 1.0 secondMemory limit: 64 MB We consider a geographical map with N countri ...

  3. POJ1459 Power Network(网络最大流)

                                         Power Network Time Limit: 2000MS   Memory Limit: 32768K Total S ...

  4. 文件的搜寻【转vbird】

    which (寻找『运行档』) [root@www ~]# which [-a] command 选项或参数: -a :将所有由 PATH 目录中可以找到的命令均列出,而不止第一个被找到的命令名称 分 ...

  5. (转) 解决ssh的"Write failed: Broken pipe"问题

    解决ssh的"Write failed: Broken pipe"问题   问题场景 服务器环境:阿里云 Linux CentOS 主机 客户端:Mac OSX Terminal ...

  6. POI导入

    public void import(){ XSSFWorkbook wb = new XSSFWorkbook(new File("filePath")); XSSFSheet ...

  7. Redis GEO ,GEOHASH,Spatial_index

    https://matt.sh/redis-geo http://antirez.com/latest/0 http://invece.org/ https://github.com/davidmot ...

  8. QAction类详解:

    先贴一段描述:Qt文档原文: Detailed Description The QAction class provides an abstract user interface action tha ...

  9. Unity光照

    广义地说,Unity有2种光源.1.动态光源  2.Backed Lighting 1.动态光源 就是实时计算的.只要摆光源就可以了 2.Backed Lighting 提前处理好光照贴图.贴在物体上 ...

  10. glibc下的内存管理

    在解码过程中我们也遇到了类似的问题,第一次解码的音频比较大60s,耗了3G的内存,reset之后内存并没有退还给操作系统,第二次即使解一个10s的音频 几周前我曾提到,我被项目组分配去做了一些探究li ...