.net Framework類庫越來越豐富了。伴隨vs2008已經(jīng)3.5版本了。
以前寫程序很少會去調(diào)用.net framework,不過隨著微軟的主推,和不斷對其進行擴展。
其功能正在逐漸強大,使用更加簡潔和方便。
這里通過對注冊表的操作。我們來看看vc++.net程序。
說明:以下代碼在vs2005下編譯。
簡單的說傳統(tǒng)的c++如何調(diào)用net frame.
一些預(yù)備知識:
^:vc2005下,聲明托管堆(the managed heap)上對象的句柄。
在vc++2002和vc++2003下,聲明托管堆上對象的句柄是用“__gc *”表示。
為什么會出現(xiàn)"^"符號呢?
在netframe下,為了保持托管堆上的對象的引用能夠被垃圾收集器跟蹤,且當(dāng)這個對象被移動的時候,這個句柄可以被及時的更新。而傳統(tǒng)的指針和引用無法被正確跟蹤,所以產(chǎn)生了^來表示一個托管堆上對象的句柄。
其可以用->來訪問其成員。
什么時候用 ^ 呢?
來看看RegisterKey的聲明
[ComVisibleAttribute(true)]
public ref class RegistryKey sealed : public MarshalByRefObject, IDisposable
看到ref了吧,
ref:聲明一個托管類或者結(jié)構(gòu)。
看到它,就聲明^
以下三個例子應(yīng)該很容易看懂了。
1. 將數(shù)據(jù)寫入注冊表
using namespace System;
using namespace Microsoft::Win32;
int main()
{
// The second OpenSubKey argument indicates that
// the subkey should be writable.
RegistryKey^ rk;
//托管堆上的一個句柄
rk = Registry::CurrentUser->OpenSubKey("Software", true);
//靜態(tài)成員可以通過其類名直接訪問
if (!rk)
{
Console::WriteLine("Failed to open CurrentUser/Software key");
return -1;
}
RegistryKey^ nk = rk->CreateSubKey("NewRegKey");
if (!nk)
{
Console::WriteLine("Failed to create 'NewRegKey'");
return -1;
}
String^ newValue = "NewValue";
try
{
nk->SetValue("NewKey", newValue);
nk->SetValue("NewKey2", 44);
}
catch (Exception^)
{
Console::WriteLine("Failed to set new values in 'NewRegKey'");
return -1;
}
Console::WriteLine("New key created.");
Console::Write("Use REGEDIT.EXE to verify ");
Console::WriteLine("'CURRENTUSER/Software/NewRegKey'\n");*/
return 0;
}
2. 從注冊表中讀取數(shù)據(jù)
using namespace System;
using namespace Microsoft::Win32;
int main( )
{
array<String^>^ key = Registry::CurrentUser->GetSubKeyNames( );
Console::WriteLine("Subkeys within CurrentUser root key:");
for (int i=0; i<key->Length; i++)
{
Console::WriteLine(" {0}", key[i]);
}
Console::WriteLine("Opening subkey 'Identities'...");
RegistryKey^ rk = nullptr;
rk = Registry::CurrentUser->OpenSubKey("Identities");
if (rk==nullptr)
{
Console::WriteLine("Registry key not found - aborting");
return -1;
}
Console::WriteLine("Key/value pairs within 'Identities' key:");
array<String^>^ name = rk->GetValueNames( );
for (int i=0; i<name->Length; i++)
{
String^ value = rk->GetValue(name[i])->ToString();
Console::WriteLine(" {0} = {1}", name[i], value);
}
return 0;
}
3. 從注冊表中刪除subkey.
RegistryKey^ rk;
rk = Registry::CurrentUser->OpenSubKey("Software", true);
if (!rk)
{
Console::WriteLine("Failed to open CurrentUser/Software key");
return -1;
}
rk->DeleteSubKey("NewRegKey");
寫在后面的話:
之所有寫這個標(biāo)題,而不寫有關(guān)CLI的,國內(nèi)關(guān)于cli探討還是比較少的。
既然,有人有好的建議,加一個副標(biāo)題好了。