=================================版权声明=================================

版权声明:本文为博主原创文章 未经许可不得转载 

请通过右侧公告中的“联系邮箱(wlsandwho@foxmail.com)”联系我

未经作者授权勿用于学术性引用。

未经作者授权勿用于商业出版、商业印刷、商业引用以及其他商业用途。                

本文不定期修正完善,为保证内容正确,建议移步原文处阅读。                                                               <--------总有一天我要自己做一个模板干掉这只土豆

本文链接:

耻辱墙:http://www.cnblogs.com/wlsandwho/p/4206472.html

=======================================================================

第二十二章 使用非托管代码

  System::Runtime::InteropServices

  GCHandle

    GCHandle::Alloc

    GCHandle::Free

  gcroot辅助模板类

    代替对GCHandle的直接操作

    离开作用域时销毁

  auto_gcroot

    <auto_gcroot.h>

    离开作用域时调用析构函数

  混合类

    托管类中添加指向非托管对象的指针成员

      需要为托管类声明析构函数

      ref Classs ManagedClass

      {

      public:

        ~ManagedClass(){delete m_pUnc;}

      private:

        UnManagedClass* m_pUnC;

      }

    非托管类中添加托管类

      Class UnManagedClass

      {

      public:

        UnManagedClass(gcroot<ManagedClass^> gcrMC):m_gcrMC(gcrMC){}

      private:

        gcroot<ManagedClass^> m_gcrMC;

      }

 #include "stdafx.h"
#include <gcroot.h>
#include <iostream>
#include <atlstr.h> using namespace System;
using namespace System::Runtime::InteropServices;
ref class CPerson
{
public:
CPerson(int nAge, String^ strName) :m_nAge(nAge),m_strName(strName) {} int GetAge() { return m_nAge; }
String^ GetName() { return m_strName; } private:
int m_nAge;
String ^ m_strName;
}; class CPersonInfo
{
public:
CPersonInfo(gcroot<CPerson^> gcroPerson):m_oPerson(gcroPerson){}
int GetAge() { return m_oPerson->GetAge(); }
CString GetName()
{
return m_oPerson->GetName();
} private:
gcroot<CPerson^> m_oPerson;
}; int main(array<System::String ^> ^args)
{
CPerson^ oPerson = gcnew CPerson(, L"Jack");
CPersonInfo oPersonInfo(oPerson); std::wcout << oPersonInfo.GetName().GetString() << L" " << oPersonInfo.GetAge() <<std::endl; return ;
}

  固定指针

    值不变的托管对象指针

    垃圾回收器不能移动它

    可以安全的传给非托管对象

    固定托管对象的成员造成整个托管对象都被固定

    只要存在对固定指针的引用,托管对象就会一直被固定

 #include "stdafx.h"
#include <iostream>
using namespace System; void PrintANumber(int * pNumArr)
{
std::cout << *pNumArr << std::endl;
} int main(array<System::String ^> ^args)
{
array<int>^ arrNum = gcnew array<int>{, , , , }; pin_ptr<int> pinNumArr = &arrNum[]; PrintANumber(pinNumArr); pinNumArr = nullptr; return ;
}

  dynamic_cast不匹配时返回null

  safe_cast不匹配时抛出异常

  包装了简单值的任何东西,只要大小不超过16字节就是和设计成值类型。

  装箱

    C++/CLI自动装箱

    装箱会发生值类型的按位拷贝

  拆箱

    通过强制类型转换

    safe_cast<>()

 #include "stdafx.h"

 using namespace System;

 int main(array<System::String ^> ^args)
{
int nNum = ;
Console::WriteLine(nNum); Object^ obj12 = nNum;
Console::WriteLine(obj12); int nNum12 = safe_cast<int>(obj12);
Console::WriteLine(nNum12); return ;
}

  P/Invoke

    封送  在托管代码和非托管代码之间传递数据/在托管代码和非托管代码之间自动转换 

#include "stdafx.h"                                                                

using namespace System;                                                            

using namespace System::Runtime::InteropServices;                                  

[DllImport("User32.dll",CharSet=CharSet::Auto)]                                    

//int MessageBox( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType )
int MessageBox(IntPtr hWnd, String^ lpText, String^ lpCaption, unsigned int uType); int main(array<System::String ^> ^args)
{
// Console::WriteLine(L"Hello World");
String^ strText = L"Text";
String^ strCaption = L"Caption";
MessageBox(IntPtr::Zero, strText, strCaption,0); return 0;
}
#include "stdafx.h"

using namespace System;

using namespace System::Runtime::InteropServices;

[DllImport("User32.dll", EntryPoint="MessageBox",CharSet = CharSet::Auto)]

//int MessageBox( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType )
int ShowSomething(IntPtr hWnd, String^ lpText, String^ lpCaption, unsigned int uType); int main(array<System::String ^> ^args)
{
// Console::WriteLine(L"Hello World");
String^ strText = L"Text";
String^ strCaption = L"Caption";
ShowSomething(IntPtr::Zero, strText, strCaption, 0); return 0;
}

  传递结构

    布局

      自动布局LayoutKind::Auto  让运行时优化布局 P/Invoke时不要用

      显式布局LayoutKind::Explicit  按定制的字节偏移量排列

      顺序布局LayoutKind::Sequential  托管和非托管同样的排列

#include "stdafx.h"

using namespace System;

using namespace System::Runtime::InteropServices;

[StructLayoutAttribute(LayoutKind::Sequential)]
ref class CPowerState
{
public:
System::Byte ACLineStatus;
System::Byte BatteryFlag;
System::Byte BatteryLifePercent;
System::Byte ReservedforNow;
System::UInt32 BatteryLifeTime;
System::UInt32 BatteryFullLifeTime;
}; typedef long BOOL; [DllImportAttribute("Kernel32.dll")]
BOOL GetSystemPowerStatus(CPowerState^ PS); int main(array<System::String ^> ^args)
{
// Console::WriteLine(L"Hello World");
CPowerState^ oPS=gcnew CPowerState();
BOOL bRet=GetSystemPowerStatus(oPS); return 0;
}

=======================================================================

第二十三章 特性和反射

  元数据

    不知道在说什么

  使用预定义特性类

 #pragma once

 using namespace System;

 namespace MyDll {

     public ref class CTestClass
{
// TODO: 在此处添加此类的方法。
public:
CTestClass(int nVal):m_nVal(nVal){} [ObsoleteAttribute("Use the Var Property instead",false)]
int GetVal() { return m_nVal; } property int Val
{
int get() { return m_nVal; }
} private:
int m_nVal; };
}
 using namespace System;

 using namespace MyDll;

 int main(array<System::String ^> ^args)
{
CTestClass^ oTC = gcnew CTestClass();
int nVal = oTC->GetVal();
Console::WriteLine(L"{0}",nVal); return ;
}

  定义自己的特性

    特性类

      定位参数  必选参数  只读属性

      具名参数  可选参数  读写属性

    

 // CustomAttributes.h

 #pragma once

 using namespace System;

 namespace CustomAttributes {

     [AttributeUsageAttribute(AttributeTargets::Method|AttributeTargets::Property| AttributeTargets::Class)]
public ref class DocumentationAttributes:Attribute
{
// TODO: 在此处添加此类的方法。
public:
DocumentationAttributes(String^ strText):m_strText(strText) {}; property String^ Text
{
String^ get(){return m_strText;}
} property String^ Author
{
String^ get() { return m_strAuthor; }
void set(String^ strAuthor) { m_strAuthor=strAuthor; }
}
property String^ Date
{
String^ get() { return m_strDate; }
void set(String^ strDate) { m_strDate = strDate; }
} private:
String^ m_strText;
String^ m_strAuthor;
String^ m_strDate;
};
}
 #include "stdafx.h"

 using namespace System;

 using namespace CustomAttributes;

 [DocumentationAttributes("The TestAttrs class",Author="WLS")]
ref class TestAttrs
{
public:
[DocumentationAttributes("The TestAttrs class constructor takes an integer",Author="WLS",Date="2010/01/02")]
TestAttrs(int nV)
{
m_nVal = nV;
} [DocumentationAttributes("The read-only Value property returns the value of the int class number", Author = "WLS")]
property int Value
{
int get() { return m_nVal; }
} protected:
private:
int m_nVal;
}; int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
return ;
}

  反射

    不知为何感觉少了点什么编译不通过

    而且对于C++/CLI来说,这个东西主要是用来支持别的语言吧?

 // UseAttributes.cpp: 主项目文件。

 #include "stdafx.h"

 using namespace System;

 using namespace MyDll;

 using namespace::Reflection;

 int main(array<System::String ^> ^args)
{
CTestClass^ oTC = gcnew CTestClass();
int nVal = oTC->GetVal(); Type^ t = oTC->GetType();
array<Object^>^ atts=t->GetCustomAttributes(true); array<MemberInfo^>^ mi = t->GetMembers(); for each(MemberInfo^ m in mi)
{
array<Object^>^ a = m->GetCustomAttributes(true); if (a->Length>)
{
Console::WriteLine("Attributes for member {0}", m->Name);
for each (Object^ attr in a)
{
Console::WriteLine("attribute is {0}", attr->ToString()); //DocumentationAttribute^ Da = dynamic_cast<DocumentationAttribute^>(attr); }
}
} Console::WriteLine(L"{0}",nVal); return ;
}

=======================================================================

第二十四章 兼容COM

  在.NET中使用COM

    RCW  运行时可调用包装器  封送  使用时无差别感受

 // ComWrapper.cpp: 主项目文件。

 #include "stdafx.h"

 using namespace System;

 using namespace TempConverterLib;

 int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World"); TempConverterLib::ConverterClass^ conv= gcnew TempConverterLib::ConverterClass(); double dF = conv->ConvertC2F(27.0); Console::WriteLine("27C is {0} F", dF); try
{
double dF = conv->ConvertC2F(-280.0); Console::WriteLine("-280C is {0} F", dF);
}
catch (Exception^ e)
{
Console::WriteLine("Exception from COM object:{0}", e->Message);
} return ;
}

  晚期绑定

 // LateBind.cpp: 主项目文件。

 #include "stdafx.h"

 using namespace System;

 int main(array<System::String ^> ^args)
{
Guid g = Guid("75F3EDC5-AA71-437A-ACB6-F885C29E50F7"); Type^ t = Type::GetTypeFromCLSID(g); if (t==nullptr)
{
Console::WriteLine("");
} Object^ obj = System::Activator::CreateInstance(t); array<Object^>^ argarray = { 27.0 }; try
{
Object^ result = t->InvokeMember("ConvertC2F", Reflection::BindingFlags::InvokeMethod, nullptr, obj, argarray); double dF = Convert::ToDouble(result); Console::WriteLine("27C is {0}F", dF);
}
catch (Exception^ e)
{
Console::WriteLine("");
} return ;
}

  把.NET作为COM组件使用

    CCW  COM可调用包装器

    这个书不怎么讲这部分。

=======================================================================

大体看完了,有空仔细研读扩展。做做小东西。

C++/CLI——读书笔记《Visual C++/CLI从入门到精通》 第Ⅳ部分的更多相关文章

  1. C++/CLI——读书笔记《Visual C++/CLI从入门到精通》 第Ⅱ部分

    =================================版权声明================================= 版权声明:本文为博主原创文章 未经许可不得转载  请通过右 ...

  2. C++/CLI——读书笔记《Visual C++/CLI从入门到精通》 第Ⅰ部分

    =================================版权声明================================= 版权声明:本文为博主原创文章 未经许可不得转载  请通过右 ...

  3. 《利用python进行数据分析》读书笔记--第五章 pandas入门

    http://www.cnblogs.com/batteryhp/p/5006274.html pandas是本书后续内容的首选库.pandas可以满足以下需求: 具备按轴自动或显式数据对齐功能的数据 ...

  4. <<Java RESTful Web Service实战>> 读书笔记

    <<Java RESTful Web Service实战>> 读书笔记 第一章   JAX-RS2.0入门 REST (Representational State ransf ...

  5. 4 Visual Effects 视觉效果 读书笔记 第四章

    4   Visual Effects    视觉效果        读书笔记 第四章 Well, circles and ovals are good, but how about drawing r ...

  6. 《Visual C# 从入门到精通》第一章使用变量、操作符和表达式——读书笔记

    前言: 这个笔记是我个人总结,主要是熟练自己查看<Visual C# 从入门到精通>(第8版)这本书时,懵然起总结的想法,只是总结一些知识点,在工作项目会用得上,但是对毫无C#语言基础的, ...

  7. Angular学习笔记:Angular CLI

    定义 Angular CLI:The Angular CLI is a command line interface tool that can create a project, add files ...

  8. 认识CLR [《CLR via C#》读书笔记]

    认识CLR [<CLR via C#>读书笔记] <CLR via C#>读书笔记 什么是CLR CLR的基本概念 通用语言运行平台(Common Language Runti ...

  9. CLR基础之一---认识CLR [《CLR via C#》读书笔记]

    <CLR via C#>读书笔记 什么是CLR CLR的基本概念 通用语言运行平台(Common Language Runtime,简称CLR)是微软为他们的.Net虚拟机所选用的名称.这 ...

随机推荐

  1. 修复 XE7 update1 发布 iOS 8.x 实机问题

      1. 开启工程目录下面的 Entitlement.TemplateiOS.xml 档案. 2. 加入二行: <key>application-identifier</key> ...

  2. 从钉钉微应用定制化导航栏看如何实现Hydrid App开发框架

    钉钉是阿里的一款企业应用APP,里面提供了混合微应用的SDK,这其实最好的一种APP架构模式.微信公众号浏览器JSSDK也提供了类似功能特性,在在交互性上没有钉钉深入. http://ddtalk.g ...

  3. java.lang.IllegalStateException: Failed to read Class-Path attribute from manifest of jar file:/XXX

    出现这个问题的解决方案就是将原有的jar删除  然后重新下载过一遍就可以使用了  我估计是元数据等损坏了

  4. Java一步一步构建web系统 在IDEA下用Maven搭建多模块项目

    1.需求 做一个项目会有很多模块,主要是方便复用,通过各个模块之间聚合.模块也可以独立出来,如公用类库,也可以在做其它项目中使用.该文的实例会有两个模块:分别为dallin-web模块,dallin- ...

  5. Tomcat性能调优方案

    一.操作系统调优 对于操作系统优化来说,是尽可能的增大可使用的内存容量.提高CPU的频率,保证文件系统的读写速率等.经过压力测试验证,在并发连接很多的情况下,CPU的处理能力越强,系统运行速度越快.. ...

  6. spring mvc+ELK从头开始搭建日志平台

    最近由于之前协助前公司做了点力所能及的事情,居然收到了一份贵重的端午礼物,是给我女儿的一个乐高积木,整个有7大包物件,我花了接近一天的时间一砖一瓦的组织起来,虽然很辛苦但是能够从过程中体验到乐趣.这次 ...

  7. 让你忘记 Flash 的15款精彩 HTML5 游戏

    HTML5 游戏开发是一个热门的话题,开发人员和设计人员最近经常谈论到.虽然不能迅速取代 Flash 的地位,但是 HTML5 凭借它的开放性和强大的编程能力,取代 Flash 是必然的趋势.你会看到 ...

  8. JavaScript的运动框架学习总结

    一.目录 1. 入门案例——实现匀速运动 2. 入门案例——实现缓冲运动 3. 实现任意值的运动框架v.1 4. 改进任意值的运动框架v.2 5. 改进任意值的运动框架v.3 6. 实现链式运动框架 ...

  9. 一个python线程池的源码解析

    python为了方便人们编程高度封装了很多东西,比如进程里的进程池,大大方便了人们编程的效率,但是默认却没有线程池,本人前段时间整理出一个线程池,并进行了简单的解析和注释,本人水平有限,如有错误希望高 ...

  10. DevExpress VCL 13.1.4支持Delphi /C++Builder XE5

    DevExpress VCL 13.1.4支持Delphi /C++Builder XE5 重大变化 ExpressLibrary dxHalfOfPi常数声明已经从cxGeometry单元移到了cx ...