IntPtr은 정확히 무엇입니까?
IntelliSense를 사용하고 다른 사람들의 코드를 살펴보면서이 IntPtr
유형을 보았습니다. 그것이 필요할 때마다 나는 단순히 작동하는 대부분의 기능을 null
넣거나 IntPtr.Zero
발견했습니다. 정확히 무엇이며 언제 / 왜 사용됩니까?
"기본 (플랫폼 별) 크기 정수"입니다. 내부적으로 표현 void*
되었지만 정수로 노출되어 있습니다. 관리되지 않는 포인터를 저장해야하고 unsafe
코드 를 사용하고 싶지 않을 때마다 사용할 수 있습니다 . IntPtr.Zero
효과적으로 NULL
(널 포인터)입니다.
네이티브 또는 안전하지 않은 코드에서 사용되는 메모리 주소를 저장할 수있을만큼 큰 값 유형이지만 안전한 관리 코드에서 메모리 주소로 직접 사용할 수는 없습니다.
당신은 사용할 수 IntPtr.Size
는 각각 4 또는 8 바이트를 수있는 바와 같이, 32 비트 또는 64 비트 프로세스에서 실행하고 있는지 알 수 있습니다.
예를 들면 다음과 같습니다.
고속 카메라와 인터페이스하는 C # 프로그램을 작성 중입니다. 카메라에는 이미지를 가져 와서 자동으로 컴퓨터 메모리에로드하는 자체 드라이버가 있습니다.
따라서 최신 이미지를 작업 할 프로그램으로 가져올 준비가되면 카메라 드라이버가 이미지를 물리적 메모리에 이미 저장되어있는 위치에 IntPtr을 제공하므로 시간 / 자원을 낭비하지 않아도됩니다. 이미 메모리에있는 이미지를 저장하기위한 메모리 블록. IntPtr은 이미지가 이미 어디에 있는지 보여줍니다.
직접적인 해석
을 IntPtr은 인 정수 A와 같은 크기의 포인터 .
IntPtr을 사용하여 포인터가 아닌 유형으로 포인터 값을 저장할 수 있습니다. 포인터를 사용하면 오류가 발생하기 쉬우므로 대부분의 상황에서 불법이기 때문에이 기능은 .NET에서 중요합니다. 포인터 값을 "안전한"데이터 형식으로 저장하면 안전 하지 않은 코드 세그먼트 간의 배관 이보다 안전한 고급 코드 또는 포인터를 직접 지원하지 않는 .NET 언어로 구현 될 수 있습니다.
IntPtr의 크기는 플랫폼에 따라 다르지만 시스템에서 자동으로 올바른 크기를 사용하므로이 세부 사항을 고려할 필요가 거의 없습니다.
"IntPtr"이라는 이름이 혼동 Handle
됩니다. 더 적절할 수도 있습니다. 내 초기 추측 "을 IntPtr은"포인터이었다이었다 에 정수. IntPtr 의 MSDN 설명서 는 이름의 의미에 대한 통찰력을 제공하지 않으면 서 다소 비밀리에 자세히 설명합니다.
다른 관점
는 IntPtr
두 가지 제한이있는 포인터입니다 :
- 직접 역 참조 할 수 없습니다
- 가리키는 데이터 유형을 모릅니다.
다시 말해, IntPtr
a는 void*
- 와 비슷 하지만 기본 포인터 산술에 사용할 수있는 추가 기능이 있습니다.
의 참조를 역 참조하기 위해 IntPtr
실제 포인터 ( "안전하지 않은"컨텍스트에서만 수행 할 수있는 작업)로 캐스트하거나 InteropServices.Marshal
클래스에서 제공하는 것과 같은 도우미 루틴으로 전달할 수 있습니다 . Marshal
클래스를 사용하면 명시적인 "안전하지 않은"컨텍스트에있을 필요가 없으므로 안전에 대한 환상을 갖게됩니다. 그러나 포인터 사용에 내재 된 충돌 위험을 제거하지는 않습니다.
포인터 란 무엇입니까?
모든 언어에서 포인터는 메모리 주소를 저장하는 변수 유형이며, 가리키는 주소 또는 가리키는 주소 의 값 을 알려줄 수 있습니다 .
포인터는 일종의 북 마크라고 생각할 수 있습니다. 책의 한 페이지로 빠르게 이동하는 대신 포인터를 사용하여 메모리 블록을 추적하거나 매핑합니다.
프로그램의 메모리가 65535 바이트의 큰 배열과 정확히 같다고 상상해보십시오.
포인터가 순종적으로 가리킨다
포인터는 각각 하나의 메모리 주소를 기억하므로 각각 메모리의 단일 주소를 가리 킵니다.
그룹으로서, 포인터는 모든 명령 광고 구역에 따라 메모리 주소를 기억하고 기억합니다.
당신은 그들의 왕입니다.
C #의 포인터
특히 C #에서 포인터는 0에서 65534 사이의 메모리 주소를 저장하는 정수 변수입니다.
또한 C #과 관련하여 포인터는 int 유형이므로 서명됩니다.
음수로 된 주소는 사용할 수 없으며 65534를 초과하는 주소에는 액세스 할 수 없습니다. 그렇게하면 System.AccessViolationException이 발생합니다.
MyPointer 라는 포인터 는 다음과 같이 선언됩니다.
int * MyPointer;
C #의 포인터는 int이지만 C #의 메모리 주소는 0에서 시작하여 65534까지 확장됩니다.
뾰족한 물건은 특별한주의를 기울여 처리해야합니다.
안전하지 않다는 단어 는 당신을 놀라게하기위한 것이며 아주 좋은 이유입니다. 포인터는 뾰족한 것, 칼, 축, 포인터 등과 같은 뾰족한 것들은 특별한주의를 기울여 다루어야합니다.
포인터는 프로그래머에게 시스템을 엄격하게 제어합니다. 따라서 실수는 더 심각한 결과를 초래할 수 있습니다.
포인터를 사용하려면 프로그램 속성에서 안전하지 않은 코드를 활성화해야하며 안전하지 않은 것으로 표시된 메서드 나 블록에서만 포인터를 사용해야합니다.
안전하지 않은 블록의 예
unsafe
{
// Place code carefully and responsibly here.
}
포인터 사용법
When variables or objects are declared or instantiated, they are stored in memory.
- Declare a pointer by using the * symbol prefix.
int *MyPointer;
- To get the address of a variable, you use the & symbol prefix.
MyPointer = &MyVariable;
Once an address is assigned to a pointer, the following applies:
- Without * prefix to refer to the memory address being pointed to as an int.
MyPointer = &MyVariable; // Set MyPointer to point at MyVariable
- With * prefix to get the value stored at the memory address being pointed to.
"MyPointer is pointing at " + *MyPointer;
Since a pointer is a variable that holds a memory address, this memory address can be stored in a pointer variable.
Example of pointers being used carefully and responsibly
public unsafe void PointerTest()
{
int x = 100; // Create a variable named x
int *MyPointer = &x; // Store the address of variable named x into the pointer named MyPointer
textBox1.Text = ((int)MyPointer).ToString(); // Displays the memory address stored in pointer named MyPointer
textBox2.Text = (*MyPointer).ToString(); // Displays the value of the variable named x via the pointer named MyPointer.
}
Notice the type of the pointer is an int. This is because C# interprets memory addresses as integer numbers (int).
Why is it int instead of uint?
There is no good reason.
Why use pointers?
Pointers are a lot of fun. With so much of the computer being controlled by memory, pointers empower a programmer with more control of their program's memory.
Memory monitoring.
Use pointers to read blocks of memory and monitor how the values being pointed at change over time.
Change these values responsibly and keep track of how your changes affect your computer.
MSDN tells us:
The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
The IntPtr type is CLS-compliant, while the UIntPtr type is not. Only the IntPtr type is used in the common language runtime. The UIntPtr type is provided mostly to maintain architectural symmetry with the IntPtr type.
http://msdn.microsoft.com/en-us/library/system.intptr(VS.71).aspx
Well this is the MSDN page that deals with IntPtr
.
The first line reads:
A platform-specific type that is used to represent a pointer or a handle.
As to what a pointer or handle is the page goes on to state:
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
A pointer is a reference to an area of memory that holds some data you are interested in.
A handle can be an identifier for an object and is passed between methods/classes when both sides need to access that object.
An IntPtr
is a value type that is primarily used to hold memory addresses or handles. A pointer is a memory address. A pointer can be typed (e.g. int*
) or untyped (e.g. void*
). A Windows handle is a value that is usually the same size (or smaller) than a memory address and represents a system resource (like a file or window).
참고URL : https://stackoverflow.com/questions/1148177/just-what-is-an-intptr-exactly
'IT' 카테고리의 다른 글
Javascript date.getYear ()는 2011에서 111을 반환합니까? (0) | 2020.06.01 |
---|---|
뮤텍스 예제 / 튜토리얼? (0) | 2020.06.01 |
명명 규칙 : "상태"대 "상태" (0) | 2020.06.01 |
Moq를 사용하여 단위 테스트를위한 비동기 메소드 조롱 (0) | 2020.06.01 |
활동적인 사용자의 UserDetails를 얻는 방법 (0) | 2020.06.01 |