How to write an array in IntPtr

float[,] point = new float[3, 3]{ { 0.0f, 1.0f, 0.0f}, { -1.0f, -1.0f, 0.0f}, { 1.0f, -1.0f, 0.0f} }; 

enter image description here

  • one
    Why do you need this? Maybe you just need the right P / Invoke ad? - VladD
  • @VladD Laid out the screen, it is shown there. - SVD102
  • It would be better if you provided a text description instead of a picture. - αλεχολυτ

2 answers 2

You need something like this:

 float[,] point = new float[3, 3] { ... }; fixed (float* ptr = points) { IntPtr ip = (IntPtr)ptr; // тут можно пользоваться } 

Note that address fixing will only work inside fixed . This is important: if the function to which you pass IntPtr , will remember it inside, and will use it even after the end of fixed , wait for trouble.

(Yes, it is difficult, but you chose unsafe programming yourself.)


If you need permanently fixed memory, use Marshal.AllocHGlobal . In your case it will look like this:

 IntPtr points = Marshal.AllocHGlobal(sizeof(float) * 3 * 3); float* pointptr = (float*)points; pointptr[0] = 0.0f; // первая строка pointptr[1] = 1.0f; pointptr[2] = 0.0f; pointptr[3] = -1.0f; // вторая строка pointptr[4] = -1.0f; pointptr[5] = 0.0f; pointptr[6] = 1.0f; // третья строка pointptr[7] = -1.0f; pointptr[8] = 0.0f; 

Do not forget Marshal.FreeHGlobal(points); at the point where you no longer need this memory.

There are several options. The first one is GCHandle.Alloc https://msdn.microsoft.com/ru-ru/library/system.runtime.interopservices.gchandle(v=vs.110).aspx

 TextWriter tw = System.Console.Out; GCHandle gch = GCHandle.Alloc(tw); CallBack cewp = new CallBack(CaptureEnumWindowsProc); // platform invoke will prevent delegate to be garbage collected // before call ends LibWrap.EnumWindows(cewp, GCHandle.ToIntPtr(gch)); gch.Free(); 

The second option is to copy the data using the native memory manager. By getting an array of bytes through Buffer.BlockCopy

 static void УстановитьМассивБайтВIntPtr(byte[] value, IntPtr Элемент) { // Вызвать нативный метод для выделении памяти IntPtr ВыделеннаяПамять = AutoWrap.ВыделитьПямять(value.Length); Marshal.Copy(value, 0, ВыделеннаяПамять, value.Length); Marshal.WriteIntPtr(Элемент, ВыделеннаяПамять); IntPtr текПоз = Элемент + Marshal.SizeOf<IntPtr>(); Marshal.WriteInt32(текПоз, value.Length); } 

or allocate memory via Marshal.AllocHGlobal and Marshal.Copy Method (IntPtr, Single [], Int32, Int32)