http://www.cppblog.com/mzty/archive/2007/12/24/39517.html

CLI/C++中混合类的使用

一 混合类

所谓混合类是指CLI/C++中native的Class中可以包含CLR对象,CLR的class也可以包含Naitve的对象。

1)native的class中包含CLR对象,必须通过gcroot<>或auto_gcroot<>。
2)CLR中的class中包含native的对象,必须是指针,也可以使用高手写的CAutoNativePtr智能指针。

注意:C#中不能调用CLI/C++中的Native的class。同样Native C++中也不能调用CLI/C++中的Ref的class。

二 实例

高手的CAutoNativePtr类:

    Author    :    Nishant Sivakumar
    Email    :    voidnish@gmail.com    
    Blog    :    http://blog.voidnish.com
    Web        :    http://www.voidnish.com     

    You may freely use this class as long as you include
    this copyright. 
    
    You may freely modify and use this class as long
    as you include this copyright in your modified version. 

    This code is provided "as is" without express or implied warranty. 
    
    Copyright ?Nishant Sivakumar, 2006.
    All Rights Reserved.
***/

#pragma once

template<typename T> ref class CAutoNativePtr
{
private:
    T* _ptr;

public:
    CAutoNativePtr() : _ptr(nullptr)
    {
    }

    CAutoNativePtr(T* t) : _ptr(t)
    {
    }

    CAutoNativePtr(CAutoNativePtr<T>% an) : _ptr(an.Detach())
    {
    }

    template<typename TDERIVED> 
        CAutoNativePtr(CAutoNativePtr<TDERIVED>% an) : _ptr(an.Detach())
    {
    }

    !CAutoNativePtr()
    {    
        delete _ptr;
    }

    ~CAutoNativePtr()
    {
        this->!CAutoNativePtr();
    }

    CAutoNativePtr<T>% operator=(T* t)
    {
        Attach(t);
        return *this;
    }

    CAutoNativePtr<T>% operator=(CAutoNativePtr<T>% an)
    {
        if(this != %an)
            Attach(an.Detach());
        return *this;
    }

    template<typename TDERIVED> 
        CAutoNativePtr<T>% operator=(CAutoNativePtr<TDERIVED>% an)
    {
        Attach(an.Detach());
        return *this;
    }

    static T* operator->(CAutoNativePtr<T>% an)
    {
        return an._ptr;
    }

    static operator T*(CAutoNativePtr<T>% an)
    {
        return an._ptr;
    }

    T* Detach()
    {
        T* t = _ptr;
        _ptr = nullptr;
        return t;
    }

    void Attach(T* t)
    {
        if(t)
        {    
            if(_ptr != t)
            {
                delete _ptr;
                _ptr = t;
            }
        }
        else        {#ifdef _DEBUG            throw gcnew Exception(                "Attempting to Attach() a nullptr!");#endif        }            }    void Destroy()    {        delete _ptr;        _ptr = nullptr;    }};

测试实例之CLI/C++文件:


#pragma once
#include <string>
#include <iostream>
#include <gcroot.h>
#include <msclr/auto_gcroot.h>

#include "AutoNative.h"

using namespace System;

namespace MixedNativeAndCLIDLL {

    public class NativeClass
    {
    public:
        int *pX;    
        NativeClass(){pX = new int(10);}
        ~NativeClass()
        {
            if(pX != NULL)
            {
                delete pX;
                pX = NULL;
            }
        }        
    };

    public ref class RefClass
    {
    public:
        int x;    
        RefClass(){x = 20;}
    };

    public class MixedClass0
    {
        public:
            NativeClass nativeClass;
            //RefClass refClass; // error c3265 and error c3149
            gcroot<RefClass^> refClass1;

            std::string nativeStr;
            //System::String refStr; // error c3265 and error c3149
            gcroot<System::String^> refStr1;

            MixedClass0()
            {
                refClass1 = gcnew RefClass();
                refStr1 = gcnew System::String("i am a native class mixed some clr members.\n");
            }
            ~MixedClass0()
            {            
                delete refClass1;
                delete refStr1;
            }

            void PrintSelf()
            {
                System::Console::WriteLine("my name is MixedClass0");
                System::Console::WriteLine(refClass1->x);
                System::Console::WriteLine(refStr1);
            }
    };

    public class MixedClass1
    {
        public:
            NativeClass nativeClass;
            //RefClass refClass; // error c3265 and error c3149
            msclr::auto_gcroot<RefClass^> refClass1;

            std::string nativeStr;
            //System::String refStr; // error c3265 and error c3149
            msclr::auto_gcroot<System::String^> refStr1;

            MixedClass1()
            {
                refClass1 = gcnew RefClass();
                refStr1 = gcnew System::String("i am a native class with some clr members.\n");
            }
            ~MixedClass1()
            {
                // no need to delete.            }                    void PrintSelf()            {                System::Console::WriteLine("my name is MixedClass1");                System::Console::WriteLine(refClass1->x);                System::Console::WriteLine(refStr1);            }    };    public ref class MixedClass2    {        public:            //NativeClass nativeClass; // error c4368            NativeClass * nativeClass1;            RefClass^ refClass;                         //std::string nativeStr; // error c4368            std::string *nativeStr1;            System::String^ refStr; //                 MixedClass2()            {                nativeClass1 = new NativeClass();                nativeStr1 = new std::string("i am a clr class with some native members.\n");            }            ~MixedClass2()            {                delete nativeClass1;                delete nativeStr1;            }            !MixedClass2(){}            void PrintSelf()            {                System::Console::WriteLine("my name is MixedClass2");                std::cout<<*(nativeClass1->pX)<<std::endl;                std::cout<<*nativeStr1<<std::endl;                            }    };        public ref class MixedClass3    {        public:            //NativeClass nativeClass; // error c4368            CAutoNativePtr<NativeClass> nativeClass1;            RefClass^ refClass;                         //std::string nativeStr; // error c4368            CAutoNativePtr<std::string> nativeStr1;            System::String^ refStr; //                 MixedClass3()            {                nativeClass1 = new NativeClass();                nativeStr1 = new std::string("i am a clr class with some native members.\n");            }            ~MixedClass3(){}            !MixedClass3(){}            void PrintSelf()            {                System::Console::WriteLine("my name is MixedClass3");                std::cout<<*(nativeClass1->pX)<<std::endl;                std::cout<<*nativeStr1<<std::endl;                            }    };}

测试实例之C#调用文件:

using System.Collections.Generic;
using System.Text;

namespace CsharpTest
{
    class Program
    {
        static void Main(string[] args)
        {
            MixedNativeAndCLIDLL.MixedClass0 mixedClass0 = new MixedNativeAndCLIDLL.MixedClass0();
            //mixedClass0.PrintSelf();
            MixedNativeAndCLIDLL.MixedClass1 mixedClass1 = new MixedNativeAndCLIDLL.MixedClass1();
            //mixedClass1.PrintSelf();
            MixedNativeAndCLIDLL.MixedClass2 mixedClass2 = new MixedNativeAndCLIDLL.MixedClass2();
            mixedClass2.PrintSelf();
            MixedNativeAndCLIDLL.MixedClass3 mixedClass3 = new MixedNativeAndCLIDLL.MixedClass3();
            mixedClass3.PrintSelf();
        }
    }
}

三 代码下载

http://www.cppblog.com/Files/mzty/MixedNativeAndCLITest.rar

CLI/C++中混合类的使用【转】的更多相关文章

  1. JS中定义类的方法

    JS中定义类的方式有很多种: 1.工厂方式    function Car(){     var ocar = new Object;     ocar.color = "blue" ...

  2. sass中 混合宏 VS 继承 VS 占位符 各自的使用时机和特点

    初学者都常常纠结于这个问题“什么时候用混合宏,什么时候用继承,什么时候使用占位符?”其实他们各有各的优点与缺点,先来看看他们使用效果: a) Sass 中的混合宏使用 举例代码见 2-24 行 编译出 ...

  3. css编译工具Sass中混合宏,继承,占位符分别在什么时候使用

    //SCSS中混合宏使用 @mixin mt($var){ margin-top: $var; } .block { @include mt(5px); span { display:block; @ ...

  4. JS中定义类的方法<转>

    转载地址:http://blog.csdn.net/sdlfx/article/details/1842218 PS(个人理解): 1) 类通过prototype定义的成员(方法或属性),是每个类对象 ...

  5. Python中的类属性、实例属性与类方法、静态方法

    1.什么是类对象,实例对象 类对象:类名 实例对象:类创建的对象 2.类属性就是类对象所拥有的属性,它被所有类对象的实例对象所共有,在内存中只存在一个副本,这个和C++.Java中类的静态成员变量有点 ...

  6. Processing中PImage类和loadImage()、createImage()函数的相关解析

    聊一聊Processing中PImage类和loadImage().createImage()函数.因为要借P5做多媒体创意展示,图片是一个很重要的媒体.有必要就图片的获取和展放作总结. 首先 有一点 ...

  7. 11.mixins混合类

      一.混合类(mixins) 使用基于类的视图,最大的优势之一就创建可复用的代码 我们编写的非常类似的代码,可以抽象出来,将这部分代码放到mixin类系列中,然后作为父类提供子类继承使用 from ...

  8. Python中的类、对象、继承

    类 Python中,类的命名使用帕斯卡命名方式,即首字母大写. Python中定义类的方式如下: class 类名([父类名[,父类名[,...]]]): pass 省略父类名表示该类直接继承自obj ...

  9. 基础知识(05) -- Java中的类

    Java中的类 1.类的概念 2.类中的封装 3.对象的三大特征 4.对象状态 5.类与类之间的关系 ------------------------------------------------- ...

随机推荐

  1. OV7725学习之SCCB协议(一)

    OV7725摄像头只能作为从机,通过SCCB协议配置内置的172个寄存器.因此首先要了解的就是SCCB总线 1.SCCB协议简述 SCCB协议有两线也有三线,两线为SIO_C与SIO_D,三线为SIO ...

  2. 【LeetCode】Search Insert Position(搜索插入位置)

    这道题是LeetCode里的第35道题. 题目描述: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引.如果目标值不存在于数组中,返回它将会被按顺序插入的位置. 你可以假设数组中无重复元 ...

  3. idea中将项目与github关联

    © 版权声明:本文为博主原创文章,转载请注明出处 1.在github中创建一个账号:https://github.com/join?source=header-home 2.下载并安装git:http ...

  4. Func<T, TResult> 委托

    Func<T, TResult> 委托 Visual Studio 2008   命名空间:  System程序集:  System.Core(在 System.Core.dll 中) 语 ...

  5. BZOJ3203 保护出题人(defend)

    保护出题人(defend) 题目描述 输入 第一行两个空格隔开的正整数n和d,分别表示关数和相邻僵尸间的距离. 接下来n行每行两个空格隔开的正整数,第i + 1行为 a i和 x i,分别表示相比上一 ...

  6. bzoj1040 基环树上dp

    [bzoj1040][ZJOI2008]骑士 2014年2月26日5,2040 Description Z国的骑士团是一个很有势力的组织,帮会中汇聚了来自各地的精英.他们劫富济贫,惩恶扬善,受到社会各 ...

  7. nginx和php安装文件

    #!/usr/bin/env bash echo "=============START=====================" ## php echo '[php]yum i ...

  8. 标准IO与文件IO 的区别

    先来了解下什么是标准IO以及文件IO. 标准IO:标准I/O是ANSI C建立的一个标准I/O模型,是一个标准函数包和stdio.h头文件中的定义,具有一定的可移植性.标准IO库处理很多细节.例如缓存 ...

  9. 【转】SqlCacheDependency的使用 强大的功能

    原文发布时间为:2009-10-25 -- 来源于本人的百度文章 [由搬家工具导入]     最近我在忙于研究负载平衡、并发性容错性等性能优化问题,ASP.NET有太多强大的功能等待学习和挖掘。今天, ...

  10. PNG图片透明 IE6 解决方法

    原文发布时间为:2009-11-18 -- 来源于本人的百度文章 [由搬家工具导入] png透明解决办法 第1 种方法:定义一个样式,给某个div应用这个样式后,div的透明png背景图片自动透明了。 ...