Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# pointers vs IntPtr

Tags:

c#

.net

pointers

this is the 2nd part of the 1st question using c# pointers

so pointers in c# are 'unsafe' and not managed by the garbage collector while an IntPtr is a managed object. but why use pointers then? and when it is possible to use both approaches interchangeably?

like image 928
Ali Tarhini Avatar asked Nov 30 '10 23:11

Ali Tarhini


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

C dalam Latin berapa?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).

Apakah C termasuk bahasa pemrograman?

Bahasa C atau dibaca “si” adalah bahasa pemrograman tingkat tinggi dan general-purpose yang digunakan dalam sehari-hari. Maksud dari general-purpose adalah bisa digunakan untuk membuat program apa saja.

Bahasa C dibuat pertama kali oleh siapa dan tahun berapa?

Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.


Video Answer


1 Answers

The CLI distinguishes between managed and unmanaged pointers. A managed pointer is typed, the type of the pointed-to value is known by the runtime and only type-safe assignments are allowed. Unmanaged pointers are only directly usable in a language that supports them, C++/CLI is the best example.

The equivalent of an unmanaged pointer in the C# language is IntPtr. You can freely convert a pointer back and forth with a cast. No pointer type is associated with it even though its name sounds like "pointer to int", it is the equivalent of void* in C/C++. Using such a pointer requires pinvoke, the Marshal class or a cast to a managed pointer type.

Some code to play with:

using System;
using System.Runtime.InteropServices;

unsafe class Program {
    static void Main(string[] args) {
        int variable = 42;
        int* p = &variable;
        Console.WriteLine(*p);
        IntPtr raw = (IntPtr)p;
        Marshal.WriteInt32(raw, 666);
        p = (int*)raw;
        Console.WriteLine(*p);
        Console.ReadLine();
    }
}

Note how the unsafe keyword is appropriate here. You can call Marshal.WriteInt64() and you get no complaint whatsoever. It corrupts the stack frame.

like image 66
Hans Passant Avatar answered Sep 22 '22 05:09

Hans Passant