tell me how to use "unsafe" with c#


can you tell me how to use 'unsafe' with c# compiler. my project have to use pointer.

i was written unsafe on the c sharp script. but i saw the error CS0227: Unsafe code requires the `unsafe' command line option to be specified

where is the command line option in unity? i know that unityEditor was able to set complier option as "../MonoCompiler.framework/" before unity 2.1

I assume you have a 3rd party dll that you are trying to call; unsafe is a keyword in c# that denotes a section of unmanaged code. Inside that code block you can perform pointer operations, allocate and free memory, that sort of thing. Often, you can just use marshaling (from System.Runtime.InteropServices)

MSDN reference:

Another thing would be to make a wrapper around the dll calls you need to make. Suppose I had a dll named 'mydllname.dll', with a function defined in it that can hand me a pointer to some known amount of data, like a 256x256x32bpp texture, that I want to use. If you add the dll as a reference to the c# project, you can declare a class like this:

public class MyDllWrapper
   private static extern Int32 someDllFunctionName(ref IntPtr buffer);

   Int32[] buf = new Int32[256*256];

   public void callMyWrappedFunction()
            //the pointer that will be passed back to me by reference
            IntPtr p = new IntPtr();
            int rval = someDllFunctionName(ref p);
            //use Marshal to get the data into our managed variable
            System.Runtime.InteropServices.Marshal.Copy(p, buf, 0, buf.Length);

I don't think you can use the "unsafe" command line parameter with Unity - but maybe this forum posting helps: C++ plugin: pass arrays from C#