C \ c ++ complex of. Net programmers (3)

Source: Internet
Author: User
Tags microsoft c
Summary

This series is my personal notes for developing and learning C \ c ++ at work or after work. This article involves some content of C ++/CLI.

This article is original and first published on my personal blog:. NetProgramMember C \ c ++ complex (3). Thank you for your comments. Indicate the source for reprinting.

Although I am mainly engaged in the development of the. NET platform, I have always had a problem with C \ c ++. This article will cover some notes about hosting C ++.

Of course, C # is undoubtedly the most appropriate language for pure. NET applications. However, hosting C ++ is undoubtedly very attractive when processing native calls and hosting calls at the same time. It is often used as a bridge between the hosting world and the native world. Of course. You can say that the "platform call" feature of. NET is equally competent.

 

Hosting C ++ BASIC Language Features

In managed C ++, You need to define a managed type as follows:

Public Ref Class Arsession
{
Public :
Property Uint32 Fieldid ;
}

By default, this class implements idisposable by default. The reason is very simple. Since C ++ is used to encapsulate the managed type, the October type needs to involve unmanaged objects, implementing idisposable reduces the possibility of errors. Two types of destructor can be implemented simultaneously ":

! Arsession ( Void )
~ Arsession ( Void )

The former is like dispose (), and the latter is a C ++ native destructor.

You can reference both hosted namespaces and C ++ namespaces.

Using Namespace System ;
Using Namespace System :: Collections :: Generic ;
Using Namespace STD ;

It can also be the same as the General C ++ # include header file. The compilation process can be understood as the same as the local C ++ compilation process, but there will be a/CLR switch during compilation, and reference at least the corresponding hosted dll: mscorlib. DLL

For the managed type, use the "^" label on the right of the type identifier, for example:

String ^
Array < String ^> ^
List < Arentry ^> ^

Note that for the value type of nullable, use

Nullable < Uint32 >

Instead

Nullable < Uint32 > ^

The former can be seen in C # As uint ?, The latter will see valuetype in C #.

 

Hosted C ++ supports ref similar to C #

Int32 % Totalmatch

Add an attribute

Using Namespace System :: Runtime :: Interopservices ;
Void Foo ([ Out ] Bar ^ % X );

Applying for memory in the local heap uses the New Keyword, while applying for memory in the managed heap uses the gcnew Keyword:

Arexception ^ Exception = Gcnew Arexception ();

 

Managed C ++ Memory Management

Some of the language features described above are actually met and may not be complete. Compared with the language features, memory management brings complexity. The native C ++ has only one "Local Heap" managed by the C Runtime Library, while C ++/CLI allows simultaneous operations on local heap and managed heap. As we all know, managed stacks are managed by CLR, and the memory in managed Stacks is recycled and compressed by CLR at any time, which means that, if C # references or C ++/CLI's "handle" (that is, the variable declared by the "Dai hat type" such as string ^) are used to operate the memory of the managed heap, there is no problem, because CLR will automatically change the address to which the reference or handle points. However, if the local pointer on the local heap or stack points to the memory on the hosting stack, the CLR will not take any responsibility for address modification caused by memory compression. If this happens, using this pointer again will cause memory violations. The following figure explains this phenomenon (picture source http://www.codeproject.com/Articles/17817/C-CLI-in-Action-Using-interior-and-pinning-pointer ):

In, the local pointer pointing to the address is originally data, but when the clr gc works, data may be compressed to other places in the managed heap, instead of another memory. Typically, we need to transmit memory between the hosted byte [] and the unmanaged usigned char * object. The following sectionCodeConvert a String object to a UTF-8 encoded byte array:

Char * Marshalstringcopytochar ( String ^ Source )
{
If ( String :: Isnullorempty ( Source ))
Return Null ;
Array < Byte > ^ Vtext = System :: Text :: Encoding :: Utf8 -> Getbytes ( Source );
Pin_ptr < Unsigned Char > Ptext = & Vtext [ 0 ];
Char * Des = ( Char * ) Calloc ( Vtext -> Length + 1 , Sizeof ( Char ));
Memcpy ( Des , Ptext , Vtext -> Length );
Des [ Vtext -> Length ] = '\ 0' ;
Return Des ;
}

The above code is actually to copy part of the memory data in the managed heap to the unmanaged heap, so the key to its effectiveness is the pin_ptr <unsigned char> pointer.

In hosting C ++, you can also use the following method to replace the above implementation:

STD :: String TMP = Marshal_as < STD :: String > ( Source );

However, it seems that the conversion process is based on ANSI encoding, which is not studied in detail. But marshal_as is extensible, see: http://msdn.microsoft.com/zh-cn/library/bb384865.aspx

 

C ++ Runtime Library Problems

This is a weird problem during the development process._ CrtisvalidheappointerError. For this question, you need to understand the Microsoft C Runtime Library and its principles for managing heap memory:

First, the Microsoft C Runtime Library has many versions so far. During application execution, it is likely that multiple versions of the C Runtime Library exist in the memory, andEach C Runtime Library version maintains its own heapIn this way, if the heap memory is referenced between different runtime libraries, in debug mode, there will be a _ crtisvalidheappointer macro to prevent this operation (the release mode does not have to verify if it is not verified ). A typical scenario is that when we reference a third-party dynamic link library, if the C Runtime Library referenced by this third-party dynamic link library is inconsistent with our main program, there will be two versions of runtime libraries in the memory at the same time. Therefore, if the heap memory applied by the main program is released by other DLL, an error will be reported. Therefore, the so-called "who apply for release" principle is actually applicable here. The above error is in debug mode. It helps developers find the cross-runtime heap pointer reference problem. It is not clear whether the reference is completely illegal or only risky.

In addition, if you use static links to link to the C Runtime Library, even the same version of The Runtime Library also has two copies in the memory, there are two heap memories maintained by different runtime libraries.

From the above point of view, if you want to develop a DLL yourself, remember to provide the heap memory release function to avoid conflicts between different runtime libraries.

 

 

C ++ Template

The templates of the old c ++ version are much more complex than the C # generic version in terms of language. It is not difficult to use templates. However, if you need to design your own template classes, the problem arises. Here is a brief summary of some template basics.

The template class declaration is as follows:

Template < Typename T >
Public Class Intelligentarstructar
{
Private :
T _ Struct ;
Public :
~ Intelligentarstructar ();
}

Template Class implementation (Definition ):

Template < Typename T > Intelligentarstructar < T > ::~ Intelligentarstructar (){ ... }

Template Class:

During compilation, the compiler must wait for the templateSource codeWhen used, a corresponding type is generated. This process is called the template class.

To generate a template definition, the compiler must be able to see the template declaration, template definition, and template elements at the same time. If the compiler cannot be made in the compilation phase, you can only send requests to the linker..

Let's look at a typical error:

    • Template. h: contains the template declaration.
    • Template. cpp: Include template. H, which contains the implementation (Definition) of the template)
    • Main. cpp: Include template. H, which has the template elements)

The compiler is compiling the template. in CPP, the template declaration and template definition are displayed at the same time. However, the compiler cannot generate template types because there are no template elements (because, without elements, it is impossible to know the structure size of the T type, so Binary Code cannot be generated. CPP, you can see the template declaration and the elements of the template, but there is no template definition, so it cannot be compiled.

The typical use is that the C ++ compiler does not support separate template compilation.

There are several ways to solve this problem:

    1. When there are elements, let the compiler see the template definition. A typical method is to write the template declaration and definition in the header file at the same time.
    2. It is shown in other compilation units. The template is displayed in another CPP file, so that the linker can find the template type in the Link phase.
    3. Export keyword. It is said that no compiler has been implemented.
Welcome to my GitHub homepage: http://pchou.info

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.