SlideShare ist ein Scribd-Unternehmen logo
1 von 60
C++/CLI 概觀 王建興 qing@cs.nthu.edu.tw (Email/MSN) 2007/1/25
About Qing ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
在 C++/CLI 出現前, .NET 上的 C++ 程式員恐怕只有一個字可以形容 悶
.NET 上的 C++ 程式員為什麼悶? (1/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],*http://www.codeproject.com/managedcpp/cppcliintro01.asp
.NET 上的 C++ 程式員為什麼悶? (2/2) ,[object Object],[object Object]
為什麼不學 C# 就好了? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
好消息是… .Net 上的 C++ 程式員不用再悶了
C++/CLI 所帶來的拯救 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],*http://www.codeproject.com/managedcpp/cppcliintro01.asp
何謂 C++/CLI ? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],* Stanley B. Lippman , http://msdn.microsoft.com/msdnmag/issues/06/00/PureC/default.aspx
C++/CLI 就是 C++ X CLI ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],C++ 的特點 CLI 的特點 C++/CLI 發揮 C++ 及 CLI 的相乘效果
C++/CLI 的目標就是 無接縫式的整合 Unmanaged 及 Managed Code
C++ 及 CLI 物件模型的比較 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],C++ 的靜態物件模型 CLI 的動態物件模型
C++/CLI 中的型別宣告 ,[object Object],CLR 的 enumeration type enum class E {…} CLR 的 interface type interface class I {…} CLR 的 value type value class V {…} CLR 的 reference type ref class R {…} C++ 原生類別(過去 C++ 程式員所用) class N {…} 所宣告的型別 宣告語法
C++ 與 CTS 型別的對應 N/A Boolean bool N/A Double long double N/A Double double N/A Single float UInt64 Int64 __int64 UInt32 Int32 long int UInt32 Int32 int, __int32 UInt16 Int16 short int Byte Sbyte char CTS Unsigned Type CTS Signed Type C++ Type
各型別的用途 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
例:在 C++/CLI 中宣告 Reference Type ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],多半宣告在 .h 檔裡 多半宣告在 .pp 檔裡
Handle vs. Pointer ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
透過 Handle 建構並運用 CLI 型別 ,[object Object],[object Object]
使用 Pointer 和 Handle 的差異 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
不同的兩種物件生成及運用模式 *Kate Gregory, “Moving C++ Applications to the Common Language Runtime”     Use Native Heap    Use Managed Heap   Use Stack ^ and % always * and & never Verifiability d elete delete Free gcnew new Allocate % & Reference ^ * Pointer / Handle Managed Native
於 Native/CLI 型別中混用 Pointer/Handle (1/2) ,[object Object],[object Object],ref class R { private: String ^str; } ref class R { private: std::string* str;  }
於 Native/CLI 型別中混用 Pointer/Handle (2/2) ,[object Object],[object Object],*http://www.codeproject.com/managedcpp/ijw_unmanaged.asp class N { private: gcroot<String^> str;; }
Tracking Reference Operator % ,[object Object],R1 ^pr1 = gcnew R1(); R1 %r1 =  * pr1; Console::WriteLine(r1 . ToString()); 不再是  -> 同樣使用 *
Tracking Reference 的效應 array<String^>^ arr = gcnew array<String^>(3); int i = 0; for each(String^% s in arr) s = gcnew String(i++.ToString()); for each(String^ s in arr) Console::WriteLine(s); 執行結果: 0 1 2 array<String^>^ arr = gcnew array<String^>(3); int i = 0; for each(String^ s in arr) s = gcnew String(i++.ToString()); for each(String^ s in arr) Console::WriteLine(s); 執行結果:
CLI 的 Non-Deterministic Finalization ,[object Object],[object Object],[object Object],[object Object]
Disposal ,[object Object],[object Object],[object Object],[object Object]
Deterministic Destruction ,[object Object],ref class R1 { public: R1() {} ~R1() {} protected: !R1() {}  }; constructor destructor finalizer * 注意: C++/CLI 使用了 C# 中用來表示 Finalizer 的符號來表示 Destructor
Finalizer vs. Destructor ,[object Object],[object Object],public void Dispose()//IDisposable::Dispose { GC.SuppressFinalize(this); } *http://www.codeproject.com/managedcpp/cppclidtors.asp *http://msdn2.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx
Why  SuppressFinalize?   public class FileStream : Stream { public override void Close() { // Clean up this object: flush data and close file  … // There is no reason to Finalize this object now GC.SuppressFinalize(this); } protected override void Finalize() { Close();  // Clean up this object: flush data and close file } // Rest of FileStream methods go here … } *http://www.codeproject.com/managedcpp/cppclidtors.asp 如果程式員自行呼叫了 Close() , 但 GC 又呼叫了 Finalize() 便會引發 Close() 被叫用兩次
自動進行的 Disposal { SqlConnection conn(connString); } constructor 會被呼叫 destructor 會被自動呼叫 {   SqlConnection ^pConn = gcnew SqlConnection(connString); } constructor 會被呼叫 之後就要等待 GC 動作了
C++/CLI 中的陣列 ,[object Object],[object Object],[object Object],http://www.codeproject.com/managedcpp/cppcliarrays.asp namespace stdcli::language { template<typename T, int rank = 1> ref class array : System::Array {}; }
陣列定義語法 ,[object Object],[object Object],array<String ^> ^ strArray = gcnew array<String ^>(10); for(int i=0;i<strArray->Length;i++) { strArray[i] = &quot;&quot;+i; Console::WriteLine(strArray[i]); } array<String ^, 3> ^ strArray = gcnew array<String ^, 3>(4, 3, 2); 維度 每個維度的長度
陣列的初始化 array<String^>^ strarr = gcnew array<String^> {“String1&quot;, “String2&quot;}; array<String^>^ strarr2 = {“String1&quot;, “String2&quot;}; array<Object^,2> ^ objarr = {{“String1&quot;, 1}, {“String2&quot;, 2}};
參數陣列 ,[object Object],[object Object],void testParamArray(String ^s,  ...  array<String ^>^ params) { Console::WriteLine(s+&quot;: &quot;); for(int i=0;i<params->Length;i++) Console::WriteLine(params[i]); } int main(array<System::String ^> ^args) { testParamArray(&quot;Hello&quot;, &quot;qing&quot;); testParamArray(&quot;Hello&quot;, &quot;qing&quot;, &quot;chrisma&quot;); }
Property 的語法 ref class UserAccount { public: property String^ ID { String^ get(){return id;} virtual void set(String^ value){id = value;} } private: String^ id; }; 就和 C# 的定義方式類似
Index Property 的語法 ref class OnlineUserList{ public: property UserAccount^  User[int]  { UserAccount^ get(int idx){return (UserAccount^) alUser[idx];} } OnlineUserList() { alUser = gcnew System::Collections::ArrayList(); } // …  private: System::Collections::ArrayList ^alUser; };
Refernece Type 允許單一繼承多重實作 ref class R abstract {};  public ref class R2 : R, IClone, IComparable, IDisposable, IEnumerable { };  所有 reference type 都繼承自 System::Object 最多繼承一個類別,但可以實作多個介面
Exception Handling try { throw gcnew Exception(&quot;qing&quot;); } catch(System::Exception^ e) { Console::WriteLine(e->StackTrace); }
CLR 編譯模式:共有四種可供選擇 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
在 VS 2005 中選擇編譯模式
編譯模式之間的關連性 Native CLR Code Data Machine Code CLR Data / Types Native Data / Types MSIL Code Mixed C++ /clr Native C++ Verifiable C++ /clr:safe Pure C++ /clr:pure
CLR 編譯模式帶來的應用 ,[object Object],[object Object],[object Object],[object Object]
決定 Managed/Unmanaged 的交界處 C++ managed C++ CRT, STL, etc One call to foo() Hundreds of calls C# or C++ managed C++ CRT, STL, etc One call to foo() Hundreds of calls C# C++ CRT, STL, etc Hundreds of calls C++ One call to foo() One call * Kate Gregory, “ Moving C++ Applications to the Common Language Runtime”
C++/CLI 支援 Template template<typename T1, typename T2> class NativeData { public: NativeData(T1 t1) { m_t1 = t1; } void DoStuff(T2 t2) { //... } private: T1 m_t1; }; *http://www.codeproject.com/managedcpp/cppcligenerics.asp
Tempalte 採用 Lazy Constraint (1/2) template<typename T> class Native { public: void Start(int x) { T* t = new T(); t->Bark(x); t->WagTail(); delete t; } }; 如何確定 t 有 Bark() 及 WagTail() 兩 methods 呢? *http://www.codeproject.com/managedcpp/cppcligenerics.asp
Tempalte 採用 Lazy Constraint (2/2) Native<NativeDog> d1; d1.Start(100); Native<NativePig> d2; d2.Start(100); 引發編譯器錯誤: error C2039: 'Bark' : is not a member of 'NativePig' *http://www.codeproject.com/managedcpp/cppcligenerics.asp
C++/CLI 支援 Generics generic<typename T1, typename T2> ref class GenericData { public: GenericData(T1 t1) { m_t1 = t1; } void DoStuff(T2 t2) { //... } private: T1 m_t1; }; *http://www.codeproject.com/managedcpp/cppcligenerics.asp
Generics 採用 Subtype Constraints (1/3) generic<typename T>  where T:IDog  ref class GenRef  { public: void Start(int x) { T t = Activator::CreateInstance<T>(); t->Bark(x); t->WagTail(); delete safe_cast<Object^>(t);  } }; 透過限制 T 必須實作的介面來進行約束 *http://www.codeproject.com/managedcpp/cppcligenerics.asp
Generics 採用 Subtype Constraints (2/3) ref class ClrDog : IDog { public: virtual void Bark(int Loudness) { Console::WriteLine(&quot;ClrDog::Bark {0}&quot;,Loudness); } virtual void WagTail() { Console::WriteLine(&quot;ClrDog::WagTail&quot;); } }; *http://www.codeproject.com/managedcpp/cppcligenerics.asp
Generics 採用 Subtype Constraints (3/3) GenRef<ClrDog^> g1; g1.Start(100); *http://www.codeproject.com/managedcpp/cppcligenerics.asp
使用 Reference Types 於 Template template<typename T> class CLR { public: void Start(int x) { T^ t = gcnew T(); t->Bark(x); t->WagTail(); delete t; } }; CLR<ClrDog> g2; g2.Start(100)
將 Template 宣告為 Reference Type template<typename T>  ref  class CLR2 { public: void Start(int x) { T^ t = gcnew T(); t->Bark(x); t->WagTail(); delete t; } }; CLR 2 <ClrDog> g 3 ; g 3 .Start(100) Console::WriteLine(g3.GetType()->Name); 執行結果: ClrDog::Bark 100 ClrDog::WagTail CLR2<ClrDog>
Generics Functions generic<typename T> where T:IDog void DoAll(T t) { t->Bark(0); t->WagTail(); } *http://www.codeproject.com/managedcpp/cppcligenerics.asp
Template vs. Generics ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],*http://blogs.msdn.com/branbray/archive/2003/11/19/51023.aspx
Verifiable C++ ,[object Object],[object Object],[object Object],[object Object]
使用程式庫 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
C++/CLI 的標準化現況 ,[object Object]
Reference ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thanks

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
 
Learn C Programming Language by Using GDB
Learn C Programming Language by Using GDBLearn C Programming Language by Using GDB
Learn C Programming Language by Using GDB
 
Preprocessors
Preprocessors Preprocessors
Preprocessors
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Enums in c
Enums in cEnums in c
Enums in c
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
 
Control statement in c
Control statement in cControl statement in c
Control statement in c
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
C function
C functionC function
C function
 
C and data structure
C and data structureC and data structure
C and data structure
 
Preprocessors
PreprocessorsPreprocessors
Preprocessors
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Function in c
Function in cFunction in c
Function in c
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
C程式-函式與巨集
C程式-函式與巨集C程式-函式與巨集
C程式-函式與巨集
 

Andere mochten auch

認識 C++11 新標準及使用 AMP 函式庫作平行運算
認識 C++11 新標準及使用 AMP 函式庫作平行運算認識 C++11 新標準及使用 AMP 函式庫作平行運算
認識 C++11 新標準及使用 AMP 函式庫作平行運算建興 王
 
Spring boot 5장 cli
Spring boot 5장 cliSpring boot 5장 cli
Spring boot 5장 cliChoonghyun Yang
 
Spring boot 공작소(1-4장)
Spring boot 공작소(1-4장)Spring boot 공작소(1-4장)
Spring boot 공작소(1-4장)Choonghyun Yang
 
開放原始碼的回收與再利用
開放原始碼的回收與再利用開放原始碼的回收與再利用
開放原始碼的回收與再利用建興 王
 
開發實用創新的 Android 應用程式
開發實用創新的 Android 應用程式開發實用創新的 Android 應用程式
開發實用創新的 Android 應用程式建興 王
 
T69 c++cli ネイティブライブラリラッピング入門
T69 c++cli ネイティブライブラリラッピング入門T69 c++cli ネイティブライブラリラッピング入門
T69 c++cli ネイティブライブラリラッピング入門伸男 伊藤
 
lwdba – 開放原始碼的輕量級資料庫存取程式庫
lwdba – 開放原始碼的輕量級資料庫存取程式庫lwdba – 開放原始碼的輕量級資料庫存取程式庫
lwdba – 開放原始碼的輕量級資料庫存取程式庫建興 王
 
IKVM.NET 深入敵營的 Java
IKVM.NET 深入敵營的 JavaIKVM.NET 深入敵營的 Java
IKVM.NET 深入敵營的 Java建興 王
 
在雲端上啜飲爪哇
在雲端上啜飲爪哇在雲端上啜飲爪哇
在雲端上啜飲爪哇建興 王
 
從 Java programmer 的觀點看 ruby
從 Java programmer 的觀點看 ruby從 Java programmer 的觀點看 ruby
從 Java programmer 的觀點看 ruby建興 王
 
「沙中撈金術」﹣談開放原始碼的推薦系統
「沙中撈金術」﹣談開放原始碼的推薦系統 「沙中撈金術」﹣談開放原始碼的推薦系統
「沙中撈金術」﹣談開放原始碼的推薦系統 建興 王
 
全文搜尋引擎的進階實作與應用
全文搜尋引擎的進階實作與應用全文搜尋引擎的進階實作與應用
全文搜尋引擎的進階實作與應用建興 王
 
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法Yoshifumi Kawai
 
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用Yoshifumi Kawai
 
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...Yoshifumi Kawai
 
RuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for UnityRuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for UnityYoshifumi Kawai
 
NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#Yoshifumi Kawai
 
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPCZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPCYoshifumi Kawai
 

Andere mochten auch (18)

認識 C++11 新標準及使用 AMP 函式庫作平行運算
認識 C++11 新標準及使用 AMP 函式庫作平行運算認識 C++11 新標準及使用 AMP 函式庫作平行運算
認識 C++11 新標準及使用 AMP 函式庫作平行運算
 
Spring boot 5장 cli
Spring boot 5장 cliSpring boot 5장 cli
Spring boot 5장 cli
 
Spring boot 공작소(1-4장)
Spring boot 공작소(1-4장)Spring boot 공작소(1-4장)
Spring boot 공작소(1-4장)
 
開放原始碼的回收與再利用
開放原始碼的回收與再利用開放原始碼的回收與再利用
開放原始碼的回收與再利用
 
開發實用創新的 Android 應用程式
開發實用創新的 Android 應用程式開發實用創新的 Android 應用程式
開發實用創新的 Android 應用程式
 
T69 c++cli ネイティブライブラリラッピング入門
T69 c++cli ネイティブライブラリラッピング入門T69 c++cli ネイティブライブラリラッピング入門
T69 c++cli ネイティブライブラリラッピング入門
 
lwdba – 開放原始碼的輕量級資料庫存取程式庫
lwdba – 開放原始碼的輕量級資料庫存取程式庫lwdba – 開放原始碼的輕量級資料庫存取程式庫
lwdba – 開放原始碼的輕量級資料庫存取程式庫
 
IKVM.NET 深入敵營的 Java
IKVM.NET 深入敵營的 JavaIKVM.NET 深入敵營的 Java
IKVM.NET 深入敵營的 Java
 
在雲端上啜飲爪哇
在雲端上啜飲爪哇在雲端上啜飲爪哇
在雲端上啜飲爪哇
 
從 Java programmer 的觀點看 ruby
從 Java programmer 的觀點看 ruby從 Java programmer 的觀點看 ruby
從 Java programmer 的觀點看 ruby
 
「沙中撈金術」﹣談開放原始碼的推薦系統
「沙中撈金術」﹣談開放原始碼的推薦系統 「沙中撈金術」﹣談開放原始碼的推薦系統
「沙中撈金術」﹣談開放原始碼的推薦系統
 
全文搜尋引擎的進階實作與應用
全文搜尋引擎的進階實作與應用全文搜尋引擎的進階實作與應用
全文搜尋引擎的進階實作與應用
 
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
 
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
 
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
 
RuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for UnityRuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for Unity
 
NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#
 
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPCZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
 

Ähnlich wie Introduction to C++ over CLI

C++工程实践
C++工程实践C++工程实践
C++工程实践Shuo Chen
 
xwz 2010-10-31
xwz 2010-10-31xwz 2010-10-31
xwz 2010-10-31carlxwz
 
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509tidesq
 
C++模板与泛型编程
C++模板与泛型编程C++模板与泛型编程
C++模板与泛型编程deer hope
 
Metro Style Apps from C++ Developers' View
Metro Style Apps from C++ Developers' ViewMetro Style Apps from C++ Developers' View
Metro Style Apps from C++ Developers' ViewEric ShangKuan
 
1 C入門教學
1  C入門教學1  C入門教學
1 C入門教學Sita Liu
 
Hcsm lect-20120913
Hcsm lect-20120913Hcsm lect-20120913
Hcsm lect-20120913lusecheng
 
C#语言的演化
C#语言的演化C#语言的演化
C#语言的演化TerabyteX
 
ES5 introduction
ES5 introductionES5 introduction
ES5 introductionotakustay
 
竞赛中C++语言拾遗
竞赛中C++语言拾遗竞赛中C++语言拾遗
竞赛中C++语言拾遗乐群 陈
 
Ecma script edition5-小试
Ecma script edition5-小试Ecma script edition5-小试
Ecma script edition5-小试lydiafly
 
ajax_onlinemad
ajax_onlinemadajax_onlinemad
ajax_onlinemadKitor23
 
2006年招聘试题
2006年招聘试题2006年招聘试题
2006年招聘试题yiditushe
 
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509tidesq
 
函数调用关系工具-2011-孙光福
函数调用关系工具-2011-孙光福函数调用关系工具-2011-孙光福
函数调用关系工具-2011-孙光福Wu Liang
 
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式Will Huang
 
VC++ Programming Training Lecture in Control Lab 301 of YSU
VC++ Programming Training Lecture in Control Lab 301 of YSUVC++ Programming Training Lecture in Control Lab 301 of YSU
VC++ Programming Training Lecture in Control Lab 301 of YSUGavin Gao
 

Ähnlich wie Introduction to C++ over CLI (20)

Dev307
Dev307Dev307
Dev307
 
C++工程实践
C++工程实践C++工程实践
C++工程实践
 
xwz 2010-10-31
xwz 2010-10-31xwz 2010-10-31
xwz 2010-10-31
 
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
 
C++模板与泛型编程
C++模板与泛型编程C++模板与泛型编程
C++模板与泛型编程
 
Metro Style Apps from C++ Developers' View
Metro Style Apps from C++ Developers' ViewMetro Style Apps from C++ Developers' View
Metro Style Apps from C++ Developers' View
 
1 C入門教學
1  C入門教學1  C入門教學
1 C入門教學
 
Hcsm lect-20120913
Hcsm lect-20120913Hcsm lect-20120913
Hcsm lect-20120913
 
C#语言的演化
C#语言的演化C#语言的演化
C#语言的演化
 
ES5 introduction
ES5 introductionES5 introduction
ES5 introduction
 
竞赛中C++语言拾遗
竞赛中C++语言拾遗竞赛中C++语言拾遗
竞赛中C++语言拾遗
 
Ecma script edition5-小试
Ecma script edition5-小试Ecma script edition5-小试
Ecma script edition5-小试
 
ajax_onlinemad
ajax_onlinemadajax_onlinemad
ajax_onlinemad
 
2006年招聘试题
2006年招聘试题2006年招聘试题
2006年招聘试题
 
C+
C+C+
C+
 
C#
C#C#
C#
 
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
 
函数调用关系工具-2011-孙光福
函数调用关系工具-2011-孙光福函数调用关系工具-2011-孙光福
函数调用关系工具-2011-孙光福
 
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
 
VC++ Programming Training Lecture in Control Lab 301 of YSU
VC++ Programming Training Lecture in Control Lab 301 of YSUVC++ Programming Training Lecture in Control Lab 301 of YSU
VC++ Programming Training Lecture in Control Lab 301 of YSU
 

Introduction to C++ over CLI

  • 1. C++/CLI 概觀 王建興 qing@cs.nthu.edu.tw (Email/MSN) 2007/1/25
  • 2.
  • 3.
  • 4. 在 C++/CLI 出現前, .NET 上的 C++ 程式員恐怕只有一個字可以形容 悶
  • 5.
  • 6.
  • 7.
  • 8. 好消息是… .Net 上的 C++ 程式員不用再悶了
  • 9.
  • 10.
  • 11.
  • 12. C++/CLI 的目標就是 無接縫式的整合 Unmanaged 及 Managed Code
  • 13.
  • 14.
  • 15. C++ 與 CTS 型別的對應 N/A Boolean bool N/A Double long double N/A Double double N/A Single float UInt64 Int64 __int64 UInt32 Int32 long int UInt32 Int32 int, __int32 UInt16 Int16 short int Byte Sbyte char CTS Unsigned Type CTS Signed Type C++ Type
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21. 不同的兩種物件生成及運用模式 *Kate Gregory, “Moving C++ Applications to the Common Language Runtime”   Use Native Heap    Use Managed Heap   Use Stack ^ and % always * and & never Verifiability d elete delete Free gcnew new Allocate % & Reference ^ * Pointer / Handle Managed Native
  • 22.
  • 23.
  • 24.
  • 25. Tracking Reference 的效應 array<String^>^ arr = gcnew array<String^>(3); int i = 0; for each(String^% s in arr) s = gcnew String(i++.ToString()); for each(String^ s in arr) Console::WriteLine(s); 執行結果: 0 1 2 array<String^>^ arr = gcnew array<String^>(3); int i = 0; for each(String^ s in arr) s = gcnew String(i++.ToString()); for each(String^ s in arr) Console::WriteLine(s); 執行結果:
  • 26.
  • 27.
  • 28.
  • 29.
  • 30. Why SuppressFinalize? public class FileStream : Stream { public override void Close() { // Clean up this object: flush data and close file … // There is no reason to Finalize this object now GC.SuppressFinalize(this); } protected override void Finalize() { Close(); // Clean up this object: flush data and close file } // Rest of FileStream methods go here … } *http://www.codeproject.com/managedcpp/cppclidtors.asp 如果程式員自行呼叫了 Close() , 但 GC 又呼叫了 Finalize() 便會引發 Close() 被叫用兩次
  • 31. 自動進行的 Disposal { SqlConnection conn(connString); } constructor 會被呼叫 destructor 會被自動呼叫 { SqlConnection ^pConn = gcnew SqlConnection(connString); } constructor 會被呼叫 之後就要等待 GC 動作了
  • 32.
  • 33.
  • 34. 陣列的初始化 array<String^>^ strarr = gcnew array<String^> {“String1&quot;, “String2&quot;}; array<String^>^ strarr2 = {“String1&quot;, “String2&quot;}; array<Object^,2> ^ objarr = {{“String1&quot;, 1}, {“String2&quot;, 2}};
  • 35.
  • 36. Property 的語法 ref class UserAccount { public: property String^ ID { String^ get(){return id;} virtual void set(String^ value){id = value;} } private: String^ id; }; 就和 C# 的定義方式類似
  • 37. Index Property 的語法 ref class OnlineUserList{ public: property UserAccount^ User[int] { UserAccount^ get(int idx){return (UserAccount^) alUser[idx];} } OnlineUserList() { alUser = gcnew System::Collections::ArrayList(); } // … private: System::Collections::ArrayList ^alUser; };
  • 38. Refernece Type 允許單一繼承多重實作 ref class R abstract {}; public ref class R2 : R, IClone, IComparable, IDisposable, IEnumerable { }; 所有 reference type 都繼承自 System::Object 最多繼承一個類別,但可以實作多個介面
  • 39. Exception Handling try { throw gcnew Exception(&quot;qing&quot;); } catch(System::Exception^ e) { Console::WriteLine(e->StackTrace); }
  • 40.
  • 41. 在 VS 2005 中選擇編譯模式
  • 42. 編譯模式之間的關連性 Native CLR Code Data Machine Code CLR Data / Types Native Data / Types MSIL Code Mixed C++ /clr Native C++ Verifiable C++ /clr:safe Pure C++ /clr:pure
  • 43.
  • 44. 決定 Managed/Unmanaged 的交界處 C++ managed C++ CRT, STL, etc One call to foo() Hundreds of calls C# or C++ managed C++ CRT, STL, etc One call to foo() Hundreds of calls C# C++ CRT, STL, etc Hundreds of calls C++ One call to foo() One call * Kate Gregory, “ Moving C++ Applications to the Common Language Runtime”
  • 45. C++/CLI 支援 Template template<typename T1, typename T2> class NativeData { public: NativeData(T1 t1) { m_t1 = t1; } void DoStuff(T2 t2) { //... } private: T1 m_t1; }; *http://www.codeproject.com/managedcpp/cppcligenerics.asp
  • 46. Tempalte 採用 Lazy Constraint (1/2) template<typename T> class Native { public: void Start(int x) { T* t = new T(); t->Bark(x); t->WagTail(); delete t; } }; 如何確定 t 有 Bark() 及 WagTail() 兩 methods 呢? *http://www.codeproject.com/managedcpp/cppcligenerics.asp
  • 47. Tempalte 採用 Lazy Constraint (2/2) Native<NativeDog> d1; d1.Start(100); Native<NativePig> d2; d2.Start(100); 引發編譯器錯誤: error C2039: 'Bark' : is not a member of 'NativePig' *http://www.codeproject.com/managedcpp/cppcligenerics.asp
  • 48. C++/CLI 支援 Generics generic<typename T1, typename T2> ref class GenericData { public: GenericData(T1 t1) { m_t1 = t1; } void DoStuff(T2 t2) { //... } private: T1 m_t1; }; *http://www.codeproject.com/managedcpp/cppcligenerics.asp
  • 49. Generics 採用 Subtype Constraints (1/3) generic<typename T> where T:IDog ref class GenRef { public: void Start(int x) { T t = Activator::CreateInstance<T>(); t->Bark(x); t->WagTail(); delete safe_cast<Object^>(t); } }; 透過限制 T 必須實作的介面來進行約束 *http://www.codeproject.com/managedcpp/cppcligenerics.asp
  • 50. Generics 採用 Subtype Constraints (2/3) ref class ClrDog : IDog { public: virtual void Bark(int Loudness) { Console::WriteLine(&quot;ClrDog::Bark {0}&quot;,Loudness); } virtual void WagTail() { Console::WriteLine(&quot;ClrDog::WagTail&quot;); } }; *http://www.codeproject.com/managedcpp/cppcligenerics.asp
  • 51. Generics 採用 Subtype Constraints (3/3) GenRef<ClrDog^> g1; g1.Start(100); *http://www.codeproject.com/managedcpp/cppcligenerics.asp
  • 52. 使用 Reference Types 於 Template template<typename T> class CLR { public: void Start(int x) { T^ t = gcnew T(); t->Bark(x); t->WagTail(); delete t; } }; CLR<ClrDog> g2; g2.Start(100)
  • 53. 將 Template 宣告為 Reference Type template<typename T> ref class CLR2 { public: void Start(int x) { T^ t = gcnew T(); t->Bark(x); t->WagTail(); delete t; } }; CLR 2 <ClrDog> g 3 ; g 3 .Start(100) Console::WriteLine(g3.GetType()->Name); 執行結果: ClrDog::Bark 100 ClrDog::WagTail CLR2<ClrDog>
  • 54. Generics Functions generic<typename T> where T:IDog void DoAll(T t) { t->Bark(0); t->WagTail(); } *http://www.codeproject.com/managedcpp/cppcligenerics.asp
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.