Chapter 17. Platform Interoperability and Unsafe Code


C# has great capabilities, but sometimes it still isn't sufficient and you need to escape out of all the safety it provides and step back into the world of memory addresses and pointers. C# supports this in three ways. The first way is to go through Platform Invoke (P/Invoke) and calls into APIs exposed by unmanaged DLLs. The second is through unsafe code, which enables access to memory pointers and addresses. Frequently, code uses these features in combination. The third way, which is not covered in this text, is through COM interoperability.

This chapter culminates with a small program that determines whether the computer is a virtual computer. The code requires that you do the following:

  1. Call into an operating system DLL and request allocation of a portion of memory for executing instructions

  2. Write some assembler instructions into the allocated area

  3. Inject an address location into the assembler instructions

  4. Execute the assembler code

Aside from the P/Invoke and unsafe constructs covered here, the final listing demonstrates the full power of C# and the fact that the capabilities of unmanaged code are still accessible from C# and managed code.

Beginner Topic: What Is a Virtual Computer?

A virtual computer (or virtual machine), also called a guest computer, is virtualized or emulated through software running on the host operating system and interacting with the host computer's hardware. For example, virtual computer software (such as VMWare Workstation and Microsoft Virtual PC) can be installed on a computer running a recent version of Windows. Once the software is installed, users can configure a guest computer within the software, boot it, and install an operating system as though it was a real computer, not just one virtualized with software.





Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net