M.E. BRING .NET CLR Support to C ++ Chinese version (Part 1)

zhaozj2021-02-16  41

Managed Extensions Bring .NET CLR Support To C Chinese version (Part 1)

Author: Chris Sells

Translator: glory

[Translation: The following is some of the partial noun terms in this translation. But this doesn't mean I will translate it into Chinese, depending on the context, sometimes retaining the original word of English; and, I don't mean I will be translated in the future. 】

English

This article translation

Description

Other translations

Managed

Hosted

Refer to VS Beta2

Controlled, managed

unmanaged

Unmanaged

Refer to VS Beta2

Uncontrolled, uncontrolled

Attribute

characteristic

Property, attribute information

Property

Attributes

This translation has been previously

characteristic

Box (boxing)

Pack

UNBOX (unboxing)

Unpack

Unpack

Delegate

Delegate

Agent, representative

askSEMBLY

Accessory

VS Beta2 is translated into "assembly"

By assembly, assemblies, components, components

Constructor

Constructor

Constructor

Destructor

Destructor

Destructor

EXCEPTION

abnormal

exception

Namespace

Name space

Name space

Indexer

Indexer

Index function

REFLECTION

reflection

Mapping

CLR (Common Language Runtime)

Public language operation

Public language period

GARBAGE COLLECTION

Garbage collection

Free resource recycling

GARBAGE Collector

Garbage collector

Free resource recycling procedure

Stack

Stack

There is a novice that doesn't know "stack" to refer to "stack" or "stack"

Stack

HEAP

heap

【Abstract: If you are a C older, you may be alert to Visual Studio .NET migration. However, as a new feature -C hosting extension, it provides you with the possibility of creating applications using the .NET framework. When you use Managed C , your code is managed by the public language runtime (CLR), which provides a high-level feature such as garbage collection, interoperability, and more. This article explains why you will be willing to use the hosted extension, how to use them, how to mix the hosted and unmanaged code, and how your hosted code can be used to use programs written in other languages]

The C language already has a long time. It was first developed from Bjarne Stroustroup in 1983 and later approved as an ANSI standard in 1997. In that 14 years, in order to meet a variety of platform programmers, C has evolved very much. However, even before the C standard is approved, Microsoft began to extend Visual C , and they added extensions in each new compiler to meet the special needs of programmers centered on Windows. Now, with the promotion of Microsoft .NET, the Microsoft C Compiler team once again enables C programmers to create and use the components on the new platform using their language. However, note: This is not C in your father's era, things are getting different.

(Also note that this article is based on open-available .NET Framework SDK Beta1 and Visual Studio .Net Beta1. Although concepts should be the same, .net distribution and current versions must have changed.)

.NET essence

As a Windows developer, in addition to understanding the new .NET platform, what else can not help you. Just as a review, .NET main features are: 1. Easy-to-use support capabilities, including support for cross-language inheritance, type exceptions, constructors, and public base classes.

2. Garbage collection provides optimized automatic memory management.

3. Strong version management, a variety of versions of the same component can be in peace together on the same machine or in the same process.

4. Microsoft Intermediate Language MSIL makes the code to get verification and redirection.

These features are implemented for .NET CLR, which provides these services in a stand-alone component. (CLR is a DLL executing the .NET component.) Component itself contains metadata and implementation, which is a processor related code and a mixture of IL. Metadata provides support for language interoperability, garbage collection, and version management, but also supports IL and verifiable.

C # is invented from all of the main characteristics of .NET, therefore, for it can naturally handle them, it is not surprising. For example, a simple C # class looks as follows:

// Talker.cs

Namespace MSDNMagsamples

{

Public Class Talker

{

Public String Something = "Something";

Public void saysomething () {system.console.writeline (Something);

}

}

This class can be compiled (in a file called Talker.cs):

C: /> csc / t: library /out: Talker.dll Talker.cs

You will notice that C , except for a very important difference: Once I compile the class Talker into one .NET accessory (略 的, is a DLL or EXE that is exposed .NET components, will this component Exposure to all the necessary conditions for this .NET customers (regardless of these customers, what language implementation) is to add a public keyword, no specific entry points; no need to be .NET type and C # type What maps are made, and the compiled components provide all the metadata required to expose the Talker when the .NET is running. For example, Visual Basic .NET customers can use metadata to access class Talker as follows:

'TalkerCli.vb

Public Module TalkerClient

Sub main ()

Dim t as new msdnmagsamples.talker

T.Something = "Hello, World"

T.SAYSMETHING ()

System.console.writeline ("GoodNight, Moon")

End Sub

End module

Use the following command line to compile this TalkerCli.vb file:

C: /> VBC / T: EXE /OUT: TalkerCli.exe /R: Talker.dll TalkerCli.vb

Under the phase, this simple transplant is transplanted with C Talker to C DLL, even if other C customers go to it (if there is no compiler skills and prerequisites), don't say customers in other languages. . Unfortunately, C programmers have long been blamed for this particular restriction. It can be argued that the history of the entire Windows programming can be considered as a struggle to expose components written in a language to another. DLL uses a C style function, COM uses the interface. For C programmers, implementing a DLL entry point is not a comfortable thing, because it feels insufficient to object-oriented; on the other hand, COM excessive uses object-oriented, but in addition to the interface, there is no type is standardized (translation note) : This sentence is suspicious), even if it is exposed to COM customers, it will bring huge code burden for C programmers to C programmers. Like DLL and COM, Microsoft is continuously supporting multilingual support, and they joined to .NET support to their own language and encourage other language sellers. You should be able to see your Microsoft's old love, such as Visual Basic, C and JScript, and about two third-party and research language will support .NET. In fact, on the last PDC (Mode of Translation: (Microsoft) Occupi, I was sitting next to a guy who was transplanted on .NET. If the .NET even the APL is intended to support, you can confirm that the language you choose will also run there.

Managed C customers

Of course, the language I have chosen is C , Microsoft uses an extension called C hosted to support C on .NET, more widely known, is Managed C . In Managed C , the code and components generated using the managed extension are managed by the CLR, they are collected, have version management functions, and access to other managed types, and so on. For example, a simple ManageD C program can access C # class Talker, such as you see in Table 1. You can compile this class like this:

C: /> CL / CLR TalkCli.cpp / Link / Subsystem: Console

Table 1 Access C # class Talker

// TalkerCli.cpp

// Managed C program necessary

#using

// introduced into Talker

#using

Using namespace msdnmagsamples;

void main ()

{

Talker * t = new talker ();

T-> Something = S "Hello, World";

T-> Saysomething ();

System :: Console :: WriteLine (S "GoodNight, Moon");

}

Table 2 New Managed C Keywords and Indicators

Keyword

description

__ABSTRACT

Declare a class that cannot be directly instantiated, the Managed interface is in an abstract

__box

Create a copy of a reference type for a value type

__delegate

"Function pointer" that can be bound to an instance or static method

__event

A Rallying Point for Delegate Implementations INTERESTED IN Receiving Callbacks__finally

Declare a Finally statement block

__GC

Declare a hosted type

__IDentifier

Make the keyword as an identifier (essential in a real multilingual environment)

__interface

Declare a hosted interface

__nogc

Declare an unmanaged type or a unmanaged pointer pointing to the hosted type

#pragma managed

State a code range as a hosted, allowing access to managed types. When compiling files with / CLR option, the default is hosted.

#pragma unmanaged

State a code range as unmanaged and prevent access to managed types

__pin

Prevent a hosted object from being removed by the garbage collector. When you call the managed function in the unmanaged function, sometimes it is necessary.

__property

A property member declared for a hosted class

__sealed

Prevent a class or method from being used as a base class (method). The value of the value is sealed

__TRY_CAST

If you convert illegal, throw an exception to system :: Illegalcastexception

#uing

Import accessories metadata

__Value

Declare a hosted value type

This customer example leads to several interesting points about Managed C . First, pay attention to the use of this new #using indicator. (Table 2 is a full list of Managed C keywords and indicators). The first #using indicator tells the Managed C compiler to introduce metadata that describes all core .NET types. These types are included in the top SYSTEM namespace, which contains a large number of nested classes and namespaces, and the latter grace the .NET framework, classify. The name space in Managed C is the same as in C , so you will not be surprised by the static WriteLine method for the console class in the SYSTEM name space call nested in the System :: Console :: WriteLine. The second #using indicator is introduced into my custom C # component. Here, I also use a "Using Namespace" statement that can save some typing input when I access the class Talker, just like you are in Unmanaged C .

Second, you will notice that I use main as my entry point. The Managed C program is still a C program, so the console application requires a main. Similarly, once you introduce class Talker through #using, it is the same as regular C , create an instance, set attribute, and call methods through New. The only difference is to add "S" in front of the string to indicate that they are hosted, not non-hosted. The Managed C compiler is also very happy to handle non-host strings, which will also convert ANSI and Unicode, but this will lose some efficiency, so I avoid using it. If you are interested, you can use the .NET disassembly tool ILDASM to see if the IL generated in TalkCli.exe when using the S prefix and does not use the S prefix. Usually, ILDASM is a wonderful .NET programming tool, you should be familiar with it.

Third, in order to use the hosted extension and make your code managed, you can use the new / CLR option using the compiler. If you like this in Visual Studio .NET, you can set the "Using the Managed Extension" option on the project properties page.

In general, use the .NET type in Managed C , it feels more than using COM and ATL more likely to use C local types. The real main difference is what I have not mentioned yet: What happened when you use New to create a hosted type? Why don't I invoke DELETE (do you think I forgotten)? Garbage collection

A few years ago, I escaped some work and made a test. I wrote a native COM customer, it created a COM object, access some interface, call some method, and do something about the results. Of course, in this way, I have to explicitly release the resources I have acquired, such as interface pointers, BSTR, and so on. In order to complete this test, I will transfer my code to use intelligent types (know how to manage the C classes of their resources), so I don't have to manually release my resources. By using intelligent types like ccomptr and ccombstr, I can reduce my COM customer code line of about 40%. Of course, if you like, you can write any code through a single data point. But I think you will agree that in the C code you wrote, the resource management code accounts for a significant proportion.

Some of the opportunities that walk in can not use this kind of thing. Some languages, such as the COM-based scripting language and some versions of Visual Basic before .NET, use the reference count to manage objects. Each additional reference is another lock on the object. When all references are released, the object is destroyed. Unfortunately, the reference count has a big problem - reference cycle. Because I just delivered a considerable COM-based project, I can tell you that the BUG of the reference cycle is really problematic, and it is very difficult to track. Frankly, many people don't even want to find these bugs, let alone fix them (it is a difficult job). Therefore, .NET did not take the reference count, Microsoft chose another route: garbage collection.

.NET CLR uses the garbage collector to periodically traverse all lists of created objects, let them know if they are no longer needed, call their Finalize method and return memory to the hosted pile. When I use the keyword new in Talker customers, I configure memory from the .NET hosted pile, which means that I don't have to remember to call Delete. And because the object is not tracked by reference counting, you don't have to worry about the problem of the reference cycle. Using .NET and garbage collection, Microsoft has taken the bugs of memory leaks and reference cycles from the potential bug list in your components.

Resource management

However, there is a problem when the garbage collector is playing with its magic. C programmers using intelligent types or stack-based objects are accustomed to thinking that objects are released in the scope boundary, and for managed types, they will no longer be the case.

If the resources associated with the object are just memory-based, this is not a problem. When the internal memory is urgent, the garbage collector will of course move (usually this action has previously happened before this). However, if you hold an image file handle, database connection, and socket connections, you are not in memory, these resources cannot be determined automatic recovery. In other words, even if the garbage collector may call the Finalize method of the object you hosted at a certain time, you don't know when it happened (unless you use System :: GC :: Collect to force it to play. This will cause all objects to be collected by garbage, not only the object you are being processed). If the held resources will soon be used, you can't sit and wait for the garbage collector to run. Instead, customers who hold the object of such resources must make the object to know these resources manually. Because of this, most of the types of managed managers carrying non-memory resources achieve a thing called Disposer mode. Disposer mode requires managed types of customers to call a particular method when they end, commonly referred to as Close or Dispose methods. In order to support this mode when an exception occurs, Managed C provides a __final, which provides a __final, which can guarantee whether or not an exception has occurred:

Void WriteTolog (const char * psz)

{

Mymanagedfile * file;

Try

{

File = new mymanagedfile ("log.txt");

File-> WriteLine (PSZ);

}

__finally

{

IF (file) file-> close ();

}

}

If you are a C programmer, I guess you "metamorphosis" on this first reaction. Your second reaction may ask, "Why not create this object on the stack to call Close?" Unfortunately, the hosted class cannot be created on the stack. They must be created on the hosted pile, so the garbage collector can manage them. Some of the .NET called value types can be configured on the stack, but unfortunately, they can't have a destructor. In fact, the hosted type is not a sectator in the C sense (that is, the method that is called when the object leaves its scope). They only have a Finalize method, regardless of when the garbage collector likes, they are called (this is also the first to lead this issue).

If you have the third reaction of this problem, it is swayed and returned to the non-host type. Before you leave, thank you for your lucky star - you selected the hosted C instead of C # or Visual Basic .NET, because Both can't avoid writing code tired for the shortcomings I have described. However, the convenience of Managed C is that it is also able to mix your use of managed and unmanaged types in the same file. You can create an unmanaged intelligence type that can be hosted by you. In fact, you will use Microsoft to provide gcroot in .NET SDK (defined in gcroot.h):

Template struct gcroot {...};

Class Gcroot is an unmanaged template class that can be used to cache a pointer to the hosted type. (.NET also does not support the hosted template). This is especially useful when you want to cache a managed type as a member data in an unmanaged type. (Managed C does not provide direct support for this.) Class gcroot uses a hosted class called System :: Runtime :: InteropServices :: Gchandle to control between a hosted pointer and an integer, how can gcroot How can Gcroot? Cache it. The class Gcroot also provides an operator-> to expose the hosted pointer. However, its destructor does not call Finalize to let the object know that you have finished. You can use Gcroot's specialization to achieve this purpose, as shown below: Template

Struct final_ptr: Gcroot

{

Final_ptr () {}

Final_ptr (T P): Gcroot (P) {}

~ final_ptr ()

{

Tp = Operator -> ();

IF (p) p-> finalize ();

}

}

This class is just a prototype, which may also change before the .NET platform issued. It can check its upgrade in the MSDN Online Developer Center (http://msdn.microsoft.com/net/).

Use this class to streamline customer code as follows:

Void WriteTolog (const char * psz)

{

Final_ptr file = new mymanagedfile ("log.txt");

File-> WriteLine (PSZ);

}

Writing and using this assistant's ability, showing the power of Managed C , compared to the relatively simple language such as C # and Visual Basic .NET, the last two needs to write more complex code to handle non-memory resources.

转载请注明原文地址:https://www.9cbs.com/read-27818.html

New Post(0)