24 Aralık 2017 Pazar

unsafe Anahtar Kelimesi

C Struct'i Dahil Etme
Elimizde C struct'ları olsun.
struct CustomerInfo
{
  char* Id;
  char* Name;
  char* Address;
};

struct CustomerList
{
  CustomerInfo* Info;
  CustomerList* Next;
};
Bu yapıları C# içinden kullanabilmek için şöyle yaparız.
public unsafe struct CustomerInfo
{
  public sbyte* Id;
  public sbyte* Name;
  public sbyte* Address;
 }

public unsafe struct CustomerList
{
  public CustomerInfo* Info;
  public CustomerList* Next;
};
C# Yapısının Adresini Alma
Bazı C# kodların aynı C++'taki gibi & (addressof) ve pointer şeklinde kullanılmasını sağlar. Şöyle yaparız.
public struct Foo
{
  public int bar;
};

void Main()
{
  var foo = new Foo();
  foo.bar = 5;

  unsafe
  {
    Foo * fooPtr = &foo;
    Console.WriteLine("Foo address {0:X}", *fooPtr);

    Foo anotherFoo = *fooPtr;
    Console.WriteLine("Bar= {0}", anotherFoo.bar);
  }
}


Hiç yorum yok:

Yorum Gönder