"Go, organize" C # unmanaged code

Source: Internet
Author: User

The. Net Framework is made up of two separate and interrelated parts: The CLR and the class library, the CLR is the service it provides to us, and the class library is the function it implements.
. NET most of the features----garbage collection, versioning, thread management, etc., all using the services provided by the CLR

Managed code

Managed code is actually the intermediate language (IL) code Managed. After the code is written, the compiler compiles the code into the intermediate language (IL) instead of the machine code that runs directly on your computer. The assembly (Assembly) file is responsible for encapsulating the intermediate language, and the assembly contains all the metadata that describes the method, class, and property that was created.
Managed code runs in the common language runtime (CLR). The CLR provides a real-time compiler to compile IL code into native machine code. This allows the CLR to make the code portable because. NET application's source code must be compiled into IL code that can run on any platform that provides CLR services. From the CLR's point of view, All languages are equal, as long as there is a compiler that can generate IL code, which ensures the interoperability of the various languages.

unmanaged code

Code that is executed directly by the operating system outside of the common language runtime environment. Unmanaged code must provide its own garbage collection, type checking, security support, and other services, unlike managed code, which obtains these services from the common language runtime, while unmanaged code is code that runs outside the runtime. Examples of unmanaged code are, for example, COM components, ActiveX interfaces, and Win32 API functions.

Difference:

1, managed code is an intermediate language, running on the CLR;

Unmanaged code is compiled into machine code and runs on the machine.

2, the managed code is independent of the platform and the language, can better realize the compatibility between different language platform;

Unmanaged code depends on the platform and language.

3, the managed code can enjoy the services provided by the CLR (such as security detection, garbage collection, etc.), do not need to complete these operations;

Unmanaged code needs to provide its own security detection, garbage collection and other operations.

The heap of. NET is the managed heap. There is no unmanaged heap. The reference target of a reference type is in the heap.

The value of the value type is in the stack.

The so-called system resources. Refers to: Network connection, database connection. File stream. This kind of thing.

Hosting here means being managed by the CLR, which is the heap managed by the CLR. Unmanaged resources need to be released manually, and managed resources are handled by the GC for you.

The using can track activities within an unmanaged resource cycle, and once the unmanaged resource life is discovered, the Dispose method is forced to release memory for unmanaged resources at that scope.

C # How to call unmanaged code directly, there are typically 2 ways:

1. Directly invokes the function exported from the DLL .

2. called Interface methods on COM objects

To export a function from a DLL:

A Use the C # keyword static and extern declaration methods.

b Attach the DllImport property to the method. The DllImport property allows you to specify the name of the DLL that contains the method.

C If required, specify custom marshaling information for the method's parameters and return values, which overrides the default marshaling for the. NET Framework.

usingSystem;usingSystem.Runtime.InteropServices;  Public classMssql_serverhandler {[DllImport ("Kernel32.dll")]         Public Static extern intGetShortPathName (stringpath, StringBuilder ShortPath,intshortpathlength)}

Fields for DllImportAttribute

Field

Description

Bestfitmapping

Enables or disables best bet mapping.

CallingConvention

Specifies the calling convention used to pass method parameters. The default value is WinAPI, which corresponds to the __stdcall of a 32-bit Intel-based platform.

CharSet

Controls the way name reorganization and marshaling string parameters into a function. The default value is CharSet.Ansi.

EntryPoint

Specifies the DLL entry point to invoke.

ExactSpelling

Controls whether entry points should be modified to correspond to character sets. The default values will vary for different programming languages.

PreserveSig

Controls whether the managed method signature should be converted to a return HRESULT and the return value has an unmanaged signature of an additional [out, retval] parameter.

The default value is True (the signature should not be converted).

SetLastError

Allows callers to use the Marshal.GetLastWin32Error API function to determine whether an error occurred while executing the method. In Visual Basic, the default value is true; in C # and C + +, the default value is False.

Throwonunmappablechar

Control throws an exception, converting an unmapped Unicode character to an ANSI "?" Character.

StructLayoutAttribute class

Once a member of a struct type is declared, the layout order of the members in memory in the instance is determined by the same order as the member declaration, and is always aligned by default to the member with the largest space in the structure (Align). Of course, we can also set or encode the way memory is aligned. In a. NET managed environment, the CLR provides a freer way to control layout in a struct: we can use the StructLayoutAttribute attribute on a struct to control the member's internal Save Layout

C # provides a StructLayoutAttribute class that allows you to define your own format type, where the formatted type is a struct or class member that is described by StructLayoutAttribute, in the governed code. It guarantees the expected layout information of its internal members. There are three options for layout:

Layout options
Describe
Layoutkind.automatic
In order to improve efficiency, the type members are reordered by the run state.
Note: Never use this option to invoke a dynamic link library function that is not governed.
Layoutkind.explicit
Sort type members by FieldOffset property for each domain
LayoutKind.Sequential
Sorts members of the type that appear in the non-governed memory where the jurisdiction type is defined.

[StructLayout (layoutkind.sequential, Pack = 1, CharSet = CharSet.Unicode)]

COM Interop Specific operations:

A. Writing a COM service program with ATL

B. Using TlbImp to convert an atl-written COM program into a COM DLL

Use the following command:

TlbImp, you wrote the Com.dll.

TlbImp is. The type library importer that is included with the NETFramework SDK. Using this command is a managed wrapper that generates an unmanaged COM DLL.

C. Managed client is very simple

Just new, then call the corresponding method.

"Go, organize" C # unmanaged code

Related Article

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.