System.Runtime.InteropServices.GCHandle.AddrOfPinnedObject()

Here are the examples of the csharp api System.Runtime.InteropServices.GCHandle.AddrOfPinnedObject() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1040 Examples 7

19 Source : ManagedCompressedAV1Data.cs
with MIT License
from 0xC0000054

protected override IntPtr PinBuffer()
        {
            if (!this.gcHandle.IsAllocated)
            {
                this.gcHandle = GCHandle.Alloc(this.buffer.Array, GCHandleType.Pinned);
            }

            return this.gcHandle.AddrOfPinnedObject();
        }

19 Source : AreaForm.cs
with MIT License
from 1CM69

public static Cursor LoadEmbeddedCursor(byte[] cursorResource, int imageIndex = 0)
            {
                var resourceHandle = GCHandle.Alloc(cursorResource, GCHandleType.Pinned);
                var iconImage = IntPtr.Zero;
                var cursorHandle = IntPtr.Zero;

                try
                {
                    var header = (IconHeader)Marshal.PtrToStructure(resourceHandle.AddrOfPinnedObject(), typeof(IconHeader));

                    if (imageIndex >= header.count)
                        throw new ArgumentOutOfRangeException("imageIndex");

                    var iconInfoPtr = resourceHandle.AddrOfPinnedObject() + Marshal.SizeOf(typeof(IconHeader)) + imageIndex * Marshal.SizeOf(typeof(IconInfo));
                    var info = (IconInfo)Marshal.PtrToStructure(iconInfoPtr, typeof(IconInfo));

                    iconImage = Marshal.AllocHGlobal(info.size + 4);
                    Marshal.WriteInt16(iconImage + 0, info.hotspot_x);
                    Marshal.WriteInt16(iconImage + 2, info.hotspot_y);
                    Marshal.Copy(cursorResource, info.offset, iconImage + 4, info.size);

                    cursorHandle = NativeMethods.CreateIconFromResource(iconImage, info.size + 4, false, 0x30000);
                    return new Cursor(cursorHandle);
                }
                finally
                {
                    if (cursorHandle != IntPtr.Zero)
                        NativeMethods.DestroyIcon(cursorHandle);

                    if (iconImage != IntPtr.Zero)
                        Marshal.FreeHGlobal(iconImage);

                    if (resourceHandle.IsAllocated)
                        resourceHandle.Free();
                }
            }

19 Source : UnityRemoteVideo.cs
with MIT License
from 734843327

IntPtr PinByteArray(ref GCHandle handle, byte[] array)
		{
			handle.Free ();
			handle = GCHandle.Alloc (array, GCHandleType.Pinned);
			return handle.AddrOfPinnedObject ();
		}

19 Source : OvrWrap64.Common.cs
with MIT License
from ab4d

public override void CalcEyePoses(Posef headPose, Vector3f[] hmdToEyeOffset, ref Posef[] eyePoses)
        {
            if (eyePoses == null)
                throw new ArgumentNullException("eyePoses");

            if (eyePoses.Length != 2)
                throw new ArgumentException("eyePoses array should have 2 Posef items", "eyePoses");


            GCHandle posesHandle = GCHandle.Alloc(eyePoses, GCHandleType.Pinned);
            try
            {
                SafeNativeMethods.ovr_CalcEyePoses(headPose, hmdToEyeOffset, posesHandle.AddrOfPinnedObject());
            }
            finally
            {
                posesHandle.Free();
            }
        }

19 Source : OvrWrap64.Common.cs
with MIT License
from ab4d

public override void GetEyePoses(IntPtr sessionPtr, long frameIndex, bool latencyMarker, Vector3f[] hmdToEyeOffset, ref Posef[] eyePoses, out double sensorSampleTime)
        {
            if (eyePoses == null)
                throw new ArgumentNullException("eyePoses");

            if (eyePoses.Length != 2)
                throw new ArgumentException("eyePoses array should have 2 Posef items", "eyePoses");


            GCHandle posesHandle = GCHandle.Alloc(eyePoses, GCHandleType.Pinned);
            try
            {
                sensorSampleTime = 0;
                SafeNativeMethods.ovr_GetEyePoses(sessionPtr, frameIndex, latencyMarker ? (byte)1 : (byte)0, hmdToEyeOffset, posesHandle.AddrOfPinnedObject(), ref sensorSampleTime);
            }
            finally
            {
                posesHandle.Free();
            }
        }

19 Source : OvrWrap64.Common.cs
with MIT License
from ab4d

public override Result GetBoundaryGeometry(IntPtr sessionPtr, BoundaryType boundaryType, out Vector3f[] floorPoints)
        {
            int out_FloorPointsCount = 0;

            // In first call we get number of points back (called with floorPointPtr == Zero)
            var result = SafeNativeMethods.ovr_GetBoundaryGeometry(sessionPtr, boundaryType, IntPtr.Zero, ref out_FloorPointsCount);

            if (result != Result.Success || out_FloorPointsCount == 0)
            {
                floorPoints = null;
                return result;
            }

            floorPoints = new Vector3f[out_FloorPointsCount];

            GCHandle gcHandle = GCHandle.Alloc(floorPoints, GCHandleType.Pinned);

            try
            {
                result = SafeNativeMethods.ovr_GetBoundaryGeometry(sessionPtr, boundaryType, gcHandle.AddrOfPinnedObject(), ref out_FloorPointsCount);
            }
            finally
            {
                gcHandle.Free();
            }

            return result;
        }

19 Source : OvrWrapTest.cs
with MIT License
from ab4d

[TestMethod]
        public void Session_SubmitControllerVibration()
        {
            IntPtr sessionPtr = CreateSession();
            replacedert.AreNotEqual(IntPtr.Zero, sessionPtr);

            byte[] samples = { 0, 64, 128, 255 };
            var gcHandle = GCHandle.Alloc(samples, GCHandleType.Pinned);

            var hapticsBuffer = new HapticsBuffer()
            {
                Samples = gcHandle.AddrOfPinnedObject(),
                SamplesCount = samples.Length,
                SubmitMode = HapticsBufferSubmitMode.Enqueue
            };

            Result result = OVR.SubmitControllerVibration(sessionPtr, ControllerType.LTouch, hapticsBuffer);

            gcHandle.Free();

            replacedert.IsTrue(result >= Result.Success, "Failed to SubmitControllerVibration");
        }

19 Source : OvrWarpDX11Test.cs
with MIT License
from ab4d

[TestMethod]
		public void Session_SubmitFrame()
		{
			IntPtr sessionPtr = CreateSession();
			replacedert.AreNotEqual(IntPtr.Zero, sessionPtr);

			// Define field of view (This is used for both left and right eye).
			FovPort fieldOfView	= new FovPort();
			fieldOfView.DownTan	 = (float) Math.Tan(0.523598776); // 0.523598776 radians = 30 degrees.
			fieldOfView.UpTan	 = (float) Math.Tan(0.523598776); // 0.523598776 radians = 30 degrees.
			fieldOfView.LeftTan	 = (float) Math.Tan(0.785398163); // 0.785398163 radians = 45 degrees.
			fieldOfView.RightTan = (float) Math.Tan(0.785398163); // 0.785398163 radians = 45 degrees.

			EyeRenderDesc renderDescLeft  = OVR.GetRenderDesc(sessionPtr, EyeType.Left, fieldOfView);
			EyeRenderDesc renderDescRight = OVR.GetRenderDesc(sessionPtr, EyeType.Left, fieldOfView);

			var viewScaleDesc = new ViewScaleDesc();
		    viewScaleDesc.HmdToEyePose0 = renderDescLeft.HmdToEyePose;
            viewScaleDesc.HmdToEyePose1 = renderDescRight.HmdToEyePose;
			viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1;

			// Determine texture size matching the field of view.
			Sizei sizeLeft  = OVR.GetFovTextureSize(sessionPtr, EyeType.Left, fieldOfView, 1.0f);
			Sizei sizeRight	= OVR.GetFovTextureSize(sessionPtr, EyeType.Right, fieldOfView, 1.0f);

			var hmdToEyeViewOffset	= new Vector3f[2];
			var poses = new Posef[2];
		    double sensorSampleTime;

			hmdToEyeViewOffset[0].X	= -0.1f;
			hmdToEyeViewOffset[1].X	= 0.1f;

			OVR.GetEyePoses(sessionPtr, 0, true, hmdToEyeViewOffset, ref poses, out sensorSampleTime);

			// Create a set of layers to submit.
			LayerEyeFov	layer	= new LayerEyeFov();
            layer.Header.Type = LayerType.EyeFov;

            Result result;

			using(TestEngine testEngine = CreateTestEngine(sessionPtr))
			{
				try
				{
					// Create a texture for the left eye.
					layer.ColorTextureLeft		 = CreateTextureSwapChain(sessionPtr, testEngine);
					layer.ViewportLeft.Position  = new Vector2i(0, 0);
					layer.ViewportLeft.Size	     = sizeLeft;
					layer.FovLeft                = fieldOfView;
					layer.RenderPoseLeft         = poses[0];

                    // Create a texture for the right eye.
					layer.ColorTextureRight		 = CreateTextureSwapChain(sessionPtr, testEngine);
					layer.ViewportRight.Position = new Vector2i(0, 0);
					layer.ViewportRight.Size	 = sizeLeft;
					layer.FovRight               = fieldOfView;
                    layer.RenderPoseRight        = poses[1];


                    // The created texture swap chain must be committed to the Oculus SDK, before using it in the
                    // call to ovr_SubmitFrame, otherwise ovr_SubmitFrame will fail.
                    result = OVR.CommitTextureSwapChain(sessionPtr, layer.ColorTextureLeft);
                    replacedert.IsTrue(result >= Result.Success);

                    result = OVR.CommitTextureSwapChain(sessionPtr, layer.ColorTextureRight);
					replacedert.IsTrue(result >= Result.Success);


                    // SubmitFrame requires pointer to an array of pointers to Layer objects
                    var layerPointers = new IntPtr[1];

                    GCHandle layerHandle = GCHandle.Alloc(layer, GCHandleType.Pinned);
                    GCHandle layerPointersHandle = GCHandle.Alloc(layerPointers, GCHandleType.Pinned);

				    layerPointers[0] = layerHandle.AddrOfPinnedObject();

                    result = OVR.SubmitFrame(sessionPtr, 0L, IntPtr.Zero, layerPointersHandle.AddrOfPinnedObject(), 1);
					replacedert.IsTrue(result >= Result.Success);

                    layerPointersHandle.Free();
                    layerHandle.Free();
                }
				finally
				{
                    if (layer.ColorTextureLeft != IntPtr.Zero)
                        OVR.DestroyTextureSwapChain(sessionPtr, layer.ColorTextureLeft);

                    if (layer.ColorTextureRight != IntPtr.Zero)
                        OVR.DestroyTextureSwapChain(sessionPtr, layer.ColorTextureRight);
				}
			}
		}

19 Source : LogEventTests.EdgeCases.cs
with MIT License
from Abc-Arbitrage

[SetUp]
        public void SetUp()
        {
            var buffer = new byte[_bufferSize];
            _bufferHandler = GCHandle.Alloc(buffer, GCHandleType.Pinned);

            var bufferSegment = new BufferSegment((byte*)_bufferHandler.AddrOfPinnedObject().ToPointer(), buffer.Length);
            _logEvent = new LogEvent(bufferSegment, 10);
            _output = new StringBuffer(128) { Culture = CultureInfo.InvariantCulture };
        }

19 Source : LogEventTests.Append.cs
with MIT License
from Abc-Arbitrage

[SetUp]
        public void SetUp()
        {
            var buffer = new byte[_bufferLength];
            _bufferHandler = GCHandle.Alloc(buffer, GCHandleType.Pinned);

            var bufferSegment = new BufferSegment((byte*)_bufferHandler.AddrOfPinnedObject().ToPointer(), buffer.Length);
            _logEvent = new LogEvent(bufferSegment, _argCapacity);
            _logEvent.Initialize(Level.Info, null, LogEventArgumentExhaustionStrategy.Allocate);
            _output = new StringBuffer(128) { Culture = CultureInfo.InvariantCulture };
        }

19 Source : OVRLipSync.cs
with MIT License
from absurd-joy

public static Result ProcessFrame(
        uint context, float[] audioBuffer, Frame frame, bool stereo = true)
    {
        if (IsInitialized() != Result.Success)
            return Result.Unknown;

        var dataType = stereo ? AudioDataType.F32_Stereo : AudioDataType.F32_Mono;
        var numSamples = (uint)(stereo ? audioBuffer.Length / 2 : audioBuffer.Length);
        var handle = GCHandle.Alloc(audioBuffer, GCHandleType.Pinned);
        var rc = ovrLipSyncDll_ProcessFrameEx(context,
                                              handle.AddrOfPinnedObject(), numSamples, dataType,
                                              ref frame.frameNumber, ref frame.frameDelay,
                                              frame.Visemes, frame.Visemes.Length,
                                              ref frame.laughterScore,
                                              null, 0
                                              );
        handle.Free();
        return (Result)rc;

    }

19 Source : OVRLipSync.cs
with MIT License
from absurd-joy

public static Result ProcessFrame(
    uint context, short[] audioBuffer, Frame frame, bool stereo = true)
    {
        if (IsInitialized() != Result.Success)
            return Result.Unknown;

        var dataType = stereo ? AudioDataType.S16_Stereo : AudioDataType.S16_Mono;
        var numSamples = (uint)(stereo ? audioBuffer.Length / 2 : audioBuffer.Length);
        var handle = GCHandle.Alloc(audioBuffer, GCHandleType.Pinned);
        var rc = ovrLipSyncDll_ProcessFrameEx(context,
                                              handle.AddrOfPinnedObject(), numSamples, dataType,
                                              ref frame.frameNumber, ref frame.frameDelay,
                                              frame.Visemes, frame.Visemes.Length,
                                              ref frame.laughterScore,
                                              null, 0
                                              );
        handle.Free();
        return (Result)rc;
    }

19 Source : OVROverlay.cs
with MIT License
from absurd-joy

private bool CreateLayer(int mipLevels, int sampleCount, OVRPlugin.EyeTextureFormat etFormat, int flags, OVRPlugin.Sizei size, OVRPlugin.OverlayShape shape)
	{
		if (!layerIdHandle.IsAllocated || layerIdPtr == IntPtr.Zero)
		{
			layerIdHandle = GCHandle.Alloc(layerId, GCHandleType.Pinned);
			layerIdPtr = layerIdHandle.AddrOfPinnedObject();
		}

		if (layerIndex == -1)
		{
			for (int i = 0; i < maxInstances; ++i)
			{
				if (instances[i] == null || instances[i] == this)
				{
					layerIndex = i;
					instances[i] = this;
					break;
				}
			}
		}

		bool needsSetup = (
			isOverridePending ||
			layerDesc.MipLevels != mipLevels ||
			layerDesc.SampleCount != sampleCount ||
			layerDesc.Format != etFormat ||
			layerDesc.Layout != layout ||
			layerDesc.LayerFlags != flags ||
			!layerDesc.TextureSize.Equals(size) ||
			layerDesc.Shape != shape);

		if (!needsSetup)
			return false;

		OVRPlugin.LayerDesc desc = OVRPlugin.CalculateLayerDesc(shape, layout, size, mipLevels, sampleCount, etFormat, flags);
		OVRPlugin.EnqueueSetupLayer(desc, compositionDepth, layerIdPtr);
		layerId = (int)layerIdHandle.Target;

		if (layerId > 0)
		{
			layerDesc = desc;
			if (isExternalSurface)
			{
				stageCount = 1;
			}
			else
			{
				stageCount = OVRPlugin.GetLayerTextureStageCount(layerId);
			}
		}

		isOverridePending = false;

		return true;
	}

19 Source : Z85.cs
with Mozilla Public License 2.0
from agebullhu

public static byte[] Decode(byte[] encoded)
		{
			int dataLen = encoded.Length;
			if (dataLen % 5 > 0)
			{
				throw new InvalidOperationException("encoded.Length must be divisible by 5");
			}
			int destLen = (Int32)(encoded.Length * .8);

			var data = GCHandle.Alloc(encoded, GCHandleType.Pinned);

			using (var dest = DispoIntPtr.Alloc(destLen))
			{
				if (IntPtr.Zero == zmq.z85_decode(dest, data.AddrOfPinnedObject()))
				{
					data.Free();
					throw new InvalidOperationException();
				}
				data.Free();

				var decoded = new byte[destLen];

				Marshal.Copy(dest, decoded, 0, decoded.Length);

				return decoded;
			}
		}

19 Source : Z85.cs
with Mozilla Public License 2.0
from agebullhu

public static byte[] Encode(byte[] decoded)
		{
			int dataLen = decoded.Length;
			if (dataLen % 4 > 0)
			{
				throw new InvalidOperationException("decoded.Length must be divisible by 4");
			}
			int destLen = (Int32)(decoded.Length * 1.25);

			var data = GCHandle.Alloc(decoded, GCHandleType.Pinned);

            // the buffer dest must be one byte larger than destLen to accomodate the null termination character
			using (var dest = DispoIntPtr.Alloc(destLen + 1))
			{
				if (IntPtr.Zero == zmq.z85_encode(dest, data.AddrOfPinnedObject(), dataLen))
				{
					data.Free();
					throw new InvalidOperationException();
				}
				data.Free();

				var bytes = new byte[destLen];

				Marshal.Copy(dest, bytes, 0, destLen);

				return bytes;
			}
		}

19 Source : ProcessExtensions.cs
with GNU General Public License v3.0
from aglab2

static object ResolveToType(byte[] bytes, Type type)
        {
            object val;

            if (type == typeof(int))
            {
                val = BitConverter.ToInt32(bytes, 0);
            }
            else if (type == typeof(uint))
            {
                val = BitConverter.ToUInt32(bytes, 0);
            }
            else if (type == typeof(float))
            {
                val = BitConverter.ToSingle(bytes, 0);
            }
            else if (type == typeof(double))
            {
                val = BitConverter.ToDouble(bytes, 0);
            }
            else if (type == typeof(byte))
            {
                val = bytes[0];
            }
            else if (type == typeof(bool))
            {
                if (bytes == null)
                    val = false;
                else
                    val = (bytes[0] != 0);
            }
            else if (type == typeof(short))
            {
                val = BitConverter.ToInt16(bytes, 0);
            }
            else // probably a struct
            {
                var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                try
                {
                    val = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), type);
                }
                finally
                {
                    handle.Free();
                }
            }

            return val;
        }

19 Source : MemoryManager.cs
with MIT License
from Akaion

internal void WriteVirtualMemory(IntPtr baseAddress, byte[] bytesToWrite)
        {
            // Adjust the protection of the virtual memory region to ensure it has write privileges
            
            var originalProtectionType = ProtectVirtualMemory(baseAddress, bytesToWrite.Length, MemoryProtection.ReadWrite);

            var bytesToWriteBufferHandle = GCHandle.Alloc(bytesToWrite, GCHandleType.Pinned);
            
            if (!WriteProcessMemory(_processHandle, baseAddress, bytesToWriteBufferHandle.AddrOfPinnedObject(), bytesToWrite.Length, IntPtr.Zero))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to write into a region of virtual memory in the remote process");
            }
            
            // Restore the original protection of the virtual memory region
            
            ProtectVirtualMemory(baseAddress, bytesToWrite.Length, originalProtectionType);

            bytesToWriteBufferHandle.Free();
        }

19 Source : MemoryManager.cs
with MIT License
from Akaion

internal void WriteVirtualMemory<TStructure>(IntPtr baseAddress, TStructure structureToWrite) where TStructure : struct
        {
            var structureSize = Marshal.SizeOf<TStructure>();
            
            // Adjust the protection of the virtual memory region to ensure it has write privileges
            
            var originalProtectionType = ProtectVirtualMemory(baseAddress, structureSize, MemoryProtection.ReadWrite);

            var structureToWriteBufferHandle = GCHandle.Alloc(structureToWrite, GCHandleType.Pinned);
            
            if (!WriteProcessMemory(_processHandle, baseAddress, structureToWriteBufferHandle.AddrOfPinnedObject(), structureSize, IntPtr.Zero))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to write into a region of virtual memory in the remote process");
            }
            
            // Restore the original protection of the virtual memory region
            
            ProtectVirtualMemory(baseAddress, structureSize, originalProtectionType);

            structureToWriteBufferHandle.Free();
        }

19 Source : UntypedBuffer.cs
with MIT License
from Alan-FGR

public unsafe void PrintDebugData(int count, Type type)
    {
        List<String> strs = new List<String>();
        for (int i = 0; i < count; i++)
        {
            String str;
            try
            {
                var cast = Activator.CreateInstance(type);
                var handle = GCHandle.Alloc(cast, GCHandleType.Pinned);
                var addr = (void*)handle.AddrOfPinnedObject();
                Buffer.MemoryCopy(At(i), addr, ElementSizeInBytes, ElementSizeInBytes);
                handle.Free();
                str = cast.ToString();
                str = str.Substring(Math.Max(0, str.Length - 16), Math.Min(str.Length, 16)).PadLeft(16, '_');
            }
            catch (Exception e)
            {
                ulong ul = 0ul;
                Buffer.MemoryCopy(At(i), &ul, ElementSizeInBytes, ElementSizeInBytes);
                str = ul.ToString("X").PadLeft(16, '0');
            }
            strs.Add(str);
        }

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine($"    {GetType()}<{type}>, elSize={ElementSizeInBytes}, bfSize={bufferSizeInBytes_}, ptr={buffer_}, unaligned={unalignedPtr_}");
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine($"      objs: {String.Join(", ", strs)}");
    }

19 Source : Program.cs
with MIT License
from altimesh

unsafe static void Main(string[] args)
        {
            HybRunner runner = HybRunner.Cuda().SetDistrib(32, 32, 16, 16, 1, 0);
            Bitmap baseImage = (Bitmap)Image.FromFile("lena512.bmp");
            int height = baseImage.Height, width = baseImage.Width;

            byte[] inputPixels = new byte[width * height];
            ReadImage(inputPixels, baseImage, width, height);
            float[] imagefloat = new float[width * height];
            for (int i = 0; i < width * height; ++i)
            {
                imagefloat[i] = (float)inputPixels[i];
            }

            IntPtr src = runner.Marshaller.MarshalManagedToNative(imagefloat);

            //bind texture
            cudaChannelFormatDesc channelDescTex = TextureHelpers.cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKind.cudaChannelFormatKindFloat);
            cudaArray_t cuArrayTex = TextureHelpers.CreateCudaArray(channelDescTex, src, width, height);
            cudaResourceDesc resDescTex = TextureHelpers.CreateCudaResourceDesc(cuArrayTex);

            //create Texture descriptor
            cudaTextureDesc texDesc = TextureHelpers.CreateCudaTextureDesc();

            //create Texture object
            cudaTextureObject_t texObj;
            cuda.CreateTextureObject(out texObj, ref resDescTex, ref texDesc);

            //bind surface
            cudaChannelFormatDesc channelDescSurf = TextureHelpers.cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKind.cudaChannelFormatKindFloat);
            cudaArray_t cuArraySurf;
            cuda.MallocArray(out cuArraySurf, ref channelDescSurf, width, height, cudaMallocArrayFlags.cudaArraySurfaceLoadStore);

            //create cudaResourceDesc
            cudaResourceDesc resDescSurf = TextureHelpers.CreateCudaResourceDesc(cuArraySurf);

            //create surface object
            cudaSurfaceObject_t surfObj;
            cuda.CreateSurfaceObject(out surfObj, ref resDescSurf);

            dynamic wrapper = runner.Wrap(new Program());

            // call kernek
            wrapper.Sobel(texObj, surfObj, width, height);


            float[] imageSobel = new float[width * height];
            for (int i = 0; i < width * height; ++i)
            {
                imageSobel[i] = 128.0F;
            }
            GCHandle handle = GCHandle.Alloc(imageSobel, GCHandleType.Pinned);
            IntPtr dest = handle.AddrOfPinnedObject();

            cuda.MemcpyFromArray(dest, cuArraySurf, 0, 0, width * height * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost);

            byte[] imageSobelByte = new byte[width * height];
            for (int i = 0; i < width * height; ++i)
            {
                imageSobelByte[i] = (byte)imageSobel[i];
            }

            SaveImage("lenaSobel512.bmp", imageSobelByte, width, height);
            cuda.DestroySurfaceObject(surfObj);
            cuda.DestroyTextureObject(texObj);
        }

19 Source : NPPIMage.cs
with MIT License
from altimesh

public static void Save(string path, IntPtr devicePtr, int width, int pitch, int height)
        {
            ushort[] arr = new ushort[height * width];
            var handle = GCHandle.Alloc(arr, GCHandleType.Pinned);
            cuda.ERROR_CHECK(cuda.Memcpy2D(handle.AddrOfPinnedObject(), width * sizeof(ushort), devicePtr, pitch, width * sizeof(ushort), height, cudaMemcpyKind.cudaMemcpyDeviceToHost));
            handle.Free();
            Bitmap bitmap = new Bitmap(width, height);
            int index = 0;
            for (int j = 0; j < height; ++j)
            {
                for (int i = 0; i < width; ++i, ++index)
                {
                    ushort pixel = arr[j * width + i];
                    bitmap.SetPixel(i, j, Color.FromArgb(pixel, pixel, pixel));
                }
            }
            bitmap.Save(path, ImageFormat.Png);
        }

19 Source : Program.cs
with MIT License
from altimesh

static void Main(string[] args)
        {
            // init CUDA
            IntPtr d;
            cuda.Malloc(out d, sizeof(int));
            cuda.Free(d);

            HybRunner runner = HybRunner.Cuda();
            cudaDeviceProp prop;
            cuda.GetDeviceProperties(out prop, 0);
            dynamic wrapped = runner.Wrap(new Program());
            runner.savereplacedembly();
            cudaStream_t stream;
            cuda.StreamCreate(out stream);

            NppStreamContext context = new NppStreamContext
            {
                hStream = stream,
                nCudaDevAttrComputeCapabilityMajor = prop.major,
                nCudaDevAttrComputeCapabilityMinor = prop.minor,
                nCudaDeviceId = 0,
                nMaxThreadsPerBlock = prop.maxThreadsPerBlock,
                nMaxThreadsPerMultiProcessor = prop.maxThreadsPerMultiProcessor,
                nMultiProcessorCount = prop.multiProcessorCount,
                nSharedMemPerBlock = 0
            };

            Random rand = new Random();

            using (NPPImage input = NPPImage.Load(inputFileName, stream))
            {
                uchar4[] output = new uchar4[input.width * input.height];
                IntPtr d_output;
                cuda.Malloc(out d_output, input.width * input.height * 4 * sizeof(byte));

                // working area 
                IntPtr oDeviceDst32u;
                size_t oDeviceDst32uPitch;
                cuda.ERROR_CHECK(cuda.MallocPitch(out oDeviceDst32u, out oDeviceDst32uPitch, input.width * sizeof(int), input.height));
                IntPtr segments;
                size_t segmentsPitch;
                cuda.ERROR_CHECK(cuda.MallocPitch(out segments, out segmentsPitch, input.width * sizeof(ushort), input.height));

                NppiSize oSizeROI = new NppiSize { width = input.width, height = input.height };
                int nBufferSize = 0;
                IntPtr pScratchBufferNPP1, pScratchBufferNPP2;

                // compute maximum label
                NPPI.ERROR_CHECK(NPPI.LabelMarkersGetBufferSize_16u_C1R(oSizeROI, out nBufferSize));
                cuda.ERROR_CHECK(cuda.Malloc(out pScratchBufferNPP1, nBufferSize));
                int maxLabel;
                NPPI.ERROR_CHECK(NPPI.LabelMarkers_16u_C1IR_Ctx(input.deviceData, input.pitch, oSizeROI, 165, NppiNorm.nppiNormInf, out maxLabel, pScratchBufferNPP1, context));


                // compress labels
                NPPI.ERROR_CHECK(NPPI.CompressMarkerLabelsGetBufferSize_16u_C1R(maxLabel, out nBufferSize));
                cuda.ERROR_CHECK(cuda.Malloc(out pScratchBufferNPP2, nBufferSize));
                NPPI.ERROR_CHECK(NPPI.CompressMarkerLabels_16u_C1IR_Ctx(input.deviceData, input.pitch, oSizeROI, maxLabel, out maxLabel, pScratchBufferNPP2, context));

                uchar4[] colormap = new uchar4[maxLabel + 1];
                for (int i = 0; i <= maxLabel; ++i)
                {
                    colormap[i] = new uchar4 { x = (byte)(rand.Next() % 256), y = (byte)(rand.Next() % 256), z = (byte)(rand.Next() % 256), w = 0 };
                }

                IntPtr d_colormap;
                cuda.Malloc(out d_colormap, (maxLabel + 1) * 4 * sizeof(byte));
                var handle = GCHandle.Alloc(colormap, GCHandleType.Pinned);
                cuda.Memcpy(d_colormap, handle.AddrOfPinnedObject(), (maxLabel + 1) * 4 * sizeof(byte), cudaMemcpyKind.cudaMemcpyHostToDevice);
                handle.Free();

                NPP_ImageSegmentationx46Programx46ColorizeLabels_ExternCWrapperStream_CUDA(
                    8 * prop.multiProcessorCount, 1, 256, 1, 1, 0, stream, // cuda configuration
                    input.deviceData, d_output, d_colormap, maxLabel + 1, input.pitch * input.height / sizeof(ushort), input.width, input.pitch / sizeof(ushort));

                handle = GCHandle.Alloc(output, GCHandleType.Pinned);
                cuda.Memcpy(handle.AddrOfPinnedObject(), d_output, input.width * input.height * sizeof(byte) * 4, cudaMemcpyKind.cudaMemcpyDeviceToHost);
                handle.Free();
                NPPImage.Save(segmentsFileName, output, input.width, input.height);
                Process.Start(segmentsFileName);

                cuda.ERROR_CHECK(cuda.Free(oDeviceDst32u));
                cuda.ERROR_CHECK(cuda.Free(segments));
                cuda.ERROR_CHECK(cuda.Free(pScratchBufferNPP1));
                cuda.ERROR_CHECK(cuda.Free(pScratchBufferNPP2));
            }
        }

19 Source : Program.cs
with MIT License
from altimesh

static void Main(string[] args)
        {
            Complex[] h_signal = new Complex[SIGNAL_SIZE];
            for (int i = 0; i < SIGNAL_SIZE; ++i)
            {
                h_signal[i].x = (float)random.NextDouble();
                h_signal[i].y = 0.0F;
            }

            Complex[] h_filter_kernel = new Complex[FILTER_KERNEL_SIZE];
            for (int i = 0; i < FILTER_KERNEL_SIZE; ++i)
            {
                h_filter_kernel[i].x = (float)random.NextDouble();
                h_filter_kernel[i].y = 0.0F;
            }

            Complex[] h_padded_signal, h_padded_filter_kernel;
            int new_size = PadData(h_signal, out h_padded_signal, SIGNAL_SIZE, h_filter_kernel, out h_padded_filter_kernel, FILTER_KERNEL_SIZE);
            int mem_size = new_size * 2 * sizeof(float);

            // pin host data an copy to device
            GCHandle signalHandle = GCHandle.Alloc(h_padded_signal, GCHandleType.Pinned);
            GCHandle kernelHandle = GCHandle.Alloc(h_padded_filter_kernel, GCHandleType.Pinned);

            IntPtr d_signal;
            cuda.ERROR_CHECK(cuda.Malloc(out d_signal, mem_size));
            IntPtr d_filter_kernel;
            cuda.ERROR_CHECK(cuda.Malloc(out d_filter_kernel, mem_size));

            cuda.ERROR_CHECK(cuda.Memcpy(d_signal, signalHandle.AddrOfPinnedObject(), mem_size, cudaMemcpyKind.cudaMemcpyHostToDevice));
            cuda.ERROR_CHECK(cuda.Memcpy(d_filter_kernel, kernelHandle.AddrOfPinnedObject(), mem_size, cudaMemcpyKind.cudaMemcpyHostToDevice));


            cufftHandle plan;
            cufft_ERROR_CHECK(cufft.Plan1d(out plan, new_size, cufftType.CUFFT_C2C, 1));

            cufftHandle plan_adv;
            size_t workSize;
            long new_size_long = new_size;
            cufft_ERROR_CHECK(cufft.Create(out plan_adv));
            cufft_ERROR_CHECK(cufft.XtMakePlanMany(plan_adv, 1, new long[1] { new_size_long }, null, 1, 1, cudaDataType_t.CUDA_C_32F, null, 1, 1, cudaDataType_t.CUDA_C_32F, 1, out workSize, cudaDataType_t.CUDA_C_32F));

            cufft_ERROR_CHECK(cufft.ExecC2C(plan, d_signal, d_signal, -1));
            cufft_ERROR_CHECK(cufft.ExecC2C(plan_adv, d_filter_kernel, d_filter_kernel, -1));

            dynamic wrapped = HybRunner.Cuda().SetDistrib(32, 256).Wrap(new Program());
            wrapped.ComplexPointwiseMulAndScale(d_signal, d_filter_kernel, new_size, 1.0F / new_size);

            cuda.ERROR_CHECK(cuda.GetLastError());
            
            cufft_ERROR_CHECK(cufft.ExecC2C(plan, d_signal, d_signal, 1));

            cuda.ERROR_CHECK(cuda.Memcpy(signalHandle.AddrOfPinnedObject(), d_signal, mem_size, cudaMemcpyKind.cudaMemcpyDeviceToHost));
            
            Complex[] h_convolved_signal_ref = new Complex[SIGNAL_SIZE];
            Convolve(h_signal, SIGNAL_SIZE, h_filter_kernel, FILTER_KERNEL_SIZE, h_convolved_signal_ref);

            bool bResult = CompareL2(h_convolved_signal_ref, h_padded_signal, 1.0E-5F);

            cufft_ERROR_CHECK(cufft.Destroy(plan));
            cufft_ERROR_CHECK(cufft.Destroy(plan_adv));
            signalHandle.Free();
            kernelHandle.Free();
            cuda.ERROR_CHECK(cuda.Free(d_signal));
            cuda.ERROR_CHECK(cuda.Free(d_filter_kernel));

            if(bResult)
            {
                Console.Error.WriteLine("ERROR");
                Environment.Exit(6);
            }

            Console.Out.WriteLine("OK");
        }

19 Source : Program.cs
with MIT License
from altimesh

unsafe static void Main(string[] args)
        {
            int nStreams = 8;
            cudaStream_t[] streams = new cudaStream_t[nStreams];
            HybRunner[] runners = new HybRunner[nStreams];
            dynamic[] wrapped = new dynamic[nStreams];
            cudaDeviceProp prop;
            cuda.GetDeviceProperties(out prop, 0);
            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamCreate(out streams[k]);

                runners[k] = HybRunner.Cuda("Streams_CUDA.dll", streams[k], CudaMarshaler.Instance).SetDistrib(16 * prop.multiProcessorCount, 128);
                wrapped[k] = runners[k].Wrap(new Program());
            }

            int N = 1024 * 1024 * 32;
            IntPtr d_a, d_b; // device pointers
            float[] a = new float[N];
            float[] b = new float[N];

            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            for(int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            int slice = N / nStreams;

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);

            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                int stop = start + slice;
                wrapped[k].Add(d_a, d_b, start, stop, 100);
            }
            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                cuda.MemcpyAsync(h_a + start * sizeof(float), d_a + start * sizeof(float), slice * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost, streams[k]);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamSynchronize(streams[k]);
                cuda.StreamDestroy(streams[k]);
            }

            for(int k = 0; k < 10; ++k)
            {
                Console.WriteLine(a[k]);
            }

            handle_a.Free();
            handle_b.Free();
        }

19 Source : Program.cs
with MIT License
from altimesh

unsafe static void Main(string[] args)
        {
            HybRunner runner = HybRunner.Cuda(@"Textures and Surfaces_CUDA.dll").SetDistrib(32, 32, 16, 16, 1, 0);
            Bitmap baseImage = (Bitmap)Image.FromFile("lena512.bmp");
            int height = baseImage.Height, width = baseImage.Width;

            byte[] inputPixels = new byte[width * height];
            ReadImage(inputPixels, baseImage, width, height);
            float[] imagefloat = new float[width * height];
            for (int i = 0; i < width * height; ++i)
            {
                imagefloat[i] = (float)inputPixels[i];
            }

            IntPtr src = runner.Marshaller.MarshalManagedToNative(imagefloat);

            //bind texture
            cudaChannelFormatDesc channelDescTex = TextureHelpers.cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKind.cudaChannelFormatKindFloat);
            cudaArray_t cuArrayTex = TextureHelpers.CreateCudaArray(channelDescTex, src, width, height);
            cudaResourceDesc resDescTex = TextureHelpers.CreateCudaResourceDesc(cuArrayTex);

            //create Texture descriptor
            cudaTextureDesc texDesc = TextureHelpers.CreateCudaTextureDesc();

            //create Texture object
            cudaTextureObject_t texObj;
            cuda.CreateTextureObject(out texObj, ref resDescTex, ref texDesc);

            //bind surface
            cudaChannelFormatDesc channelDescSurf = TextureHelpers.cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKind.cudaChannelFormatKindFloat);
            cudaArray_t cuArraySurf;
            cuda.MallocArray(out cuArraySurf, ref channelDescSurf, width, height, cudaMallocArrayFlags.cudaArraySurfaceLoadStore);

            //create cudaResourceDesc
            cudaResourceDesc resDescSurf = TextureHelpers.CreateCudaResourceDesc(cuArraySurf);

            //create surface object
            cudaSurfaceObject_t surfObj;
            cuda.CreateSurfaceObject(out surfObj, ref resDescSurf);

            dynamic wrapper = runner.Wrap(new Program());

            // call kernek
            wrapper.Sobel(texObj, surfObj, width, height);


            float[] imageSobel = new float[width * height];
            for (int i = 0; i < width * height; ++i)
            {
                imageSobel[i] = 128.0F;
            }
            GCHandle handle = GCHandle.Alloc(imageSobel, GCHandleType.Pinned);
            IntPtr dest = handle.AddrOfPinnedObject();

            cuda.MemcpyFromArray(dest, cuArraySurf, 0, 0, width * height * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost);

            byte[] imageSobelByte = new byte[width * height];
            for (int i = 0; i < width * height; ++i)
            {
                imageSobelByte[i] = (byte)imageSobel[i];
            }

            SaveImage("lenaSobel512.bmp", imageSobelByte, width, height);
            cuda.DestroySurfaceObject(surfObj);
            cuda.DestroyTextureObject(texObj);
        }

19 Source : Program.cs
with MIT License
from altimesh

unsafe static void Main(string[] args)
        {
            int nStreams = 8;
            cudaStream_t[] streams = new cudaStream_t[nStreams];
            dynamic wrapped = HybRunner.Cuda().Wrap(new Program());
            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamCreate(out streams[k]);
            }

            int N = 1024 * 1024 * 32;
            IntPtr d_a, d_b; // device pointers
            float[] a = new float[N];
            float[] b = new float[N];

            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            for(int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            int slice = N / nStreams;

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            
            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                int stop = start + slice;
                wrapped.SetStream(streams[k]).Add(d_a, d_b, start, stop, 100);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                cuda.MemcpyAsync(h_a + start * sizeof(float), d_a + start * sizeof(float), slice * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost, streams[k]);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamSynchronize(streams[k]);
                cuda.StreamDestroy(streams[k]);
            }

            for(int k = 0; k < 10; ++k)
            {
                Console.WriteLine(a[k]);
            }

            handle_a.Free();
            handle_b.Free();
        }

19 Source : 03-malloc-add.cs
with MIT License
from altimesh

unsafe static void Main(string[] args)
        {
            int N = 1024 * 1024 * 32;
            float[] a = new float[N];
            float[] b = new float[N];

            for (int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            IntPtr d_a, d_b; //device pointer
            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);

            dynamic wrapped = HybRunner.Cuda().Wrap(new Program());

            wrapped.Add(d_a, d_b, N);

            cuda.DeviceSynchronize();

            cuda.Memcpy(h_a, d_a , N * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost);

            for (int i = 0; i < N; ++i)
            {
                if (a[i] != (float)i + 1.0F)
                {
                    Console.Error.WriteLine("ERROR at {0} -- {1} != {2}", i, a[i], i + 1);
                    Environment.Exit(6); // abort
                }
            }

            handle_a.Free();
            handle_b.Free();
        }

19 Source : 04-stream-add.cs
with MIT License
from altimesh

unsafe static void Main(string[] args)
        {
            int nStreams = 8;
            cudaStream_t[] streams = new cudaStream_t[nStreams];
            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamCreate(out streams[k]);
            }

            int N = 1024 * 1024 * 32;
            float[] a = new float[N];
            float[] b = new float[N];

            for (int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            IntPtr d_a, d_b; // device pointers
            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);

            int slice = N / nStreams;

            dynamic wrapped = HybRunner.Cuda().Wrap(new Program());

            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                int stop = start + slice;
                wrapped.SetStream(streams[k]).Add(d_a, d_b, start, stop);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                cuda.MemcpyAsync(h_a + start * sizeof(float), d_a + start * sizeof(float), slice * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost, streams[k]);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamSynchronize(streams[k]);
                cuda.StreamDestroy(streams[k]);
            }

            for (int i = 0; i < N; ++i)
            {
                if (a[i] != (float)i + 1.0F)
                {
                    Console.Error.WriteLine("ERROR at {0} -- {1} != {2}", i, a[i], i + 1);
                    Environment.Exit(6); // abort
                }
            }

            handle_a.Free();
            handle_b.Free();
        }

19 Source : graybitmap.cs
with MIT License
from altimesh

public void Save(string filename)
        {
            using (BinaryWriter bw = new BinaryWriter(new FileStream(filename, FileMode.OpenOrCreate)))
            {
                // write headers
                FileHeader header = FileHeader.GrayBitmap(width, height);
                BitmapInfoHeader bih = BitmapInfoHeader.GrayBitmap(width, height);

                byte[] head = new byte[54];

                GCHandle gch = GCHandle.Alloc(header, GCHandleType.Pinned);
                Marshal.Copy(gch.AddrOfPinnedObject(), head, 0, 14);
                gch.Free();

                gch = GCHandle.Alloc(bih, GCHandleType.Pinned);
                Marshal.Copy(gch.AddrOfPinnedObject(), head, 14, 40);
                gch.Free();

                bw.Write(head, 0, 54);

                // write color table
                uint[] colors = new uint[256];
                uint color = 0;
                uint next = 0x010101;
                for (int k = 0; k < 256; ++k)
                {
                    bw.Write(color);
                    color += next;
                }

                // write data - note that bmp starts with bottom-left corner
                for (int y = 0; y < height; ++y)
                    bw.Write(data, (int)width * ((int)height - 1 - y), (int)width);
            }
        }

19 Source : NPPIMage.cs
with MIT License
from altimesh

public static NPPImage Load(string path, cudaStream_t stream)
        {
            NPPImage result = new NPPImage();
            byte[] rawData;
            if (Path.GetExtension(path).Contains("pgm"))
            {
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    using (TextReader tReader = new StreamReader(fs))
                    using (BinaryReader bReader = new BinaryReader(fs))
                    {
                        string formatLine = tReader.ReadLine(); // skip
                        string sizeLine = tReader.ReadLine();
                        string[] splitted = sizeLine.Split(' ');
                        result.width = int.Parse(splitted[0]);
                        result.height = int.Parse(splitted[1]);

                        string maxValueLine = tReader.ReadLine(); // skip
                        int pos = formatLine.Length + sizeLine.Length + maxValueLine.Length + 3;
                        fs.Seek(pos, SeekOrigin.Begin);

                        // TODO: optimize that part
                        rawData = bReader.ReadBytes((int)(fs.Length - pos));

                    }
                }
            }
            else if (Path.GetExtension(path).Contains("png"))
            {
                Bitmap image = Bitmap.FromFile(path) as Bitmap;
                result.width = image.Width;
                result.height = image.Height;
                rawData = new byte[result.width * result.height];
                int index = 0;
                for (int j = 0; j < result.height; ++j)
                {
                    for (int i = 0; i < result.width; ++i, ++index)
                    {
                        rawData[index] = image.GetPixel(i, j).R;
                    }
                }
            }
            else
            {
                throw new NotSupportedException("unsupported file format");
            }

            IntPtr deviceData;
            size_t p;
            cuda.ERROR_CHECK(cuda.MallocPitch(out deviceData, out p, result.width * sizeof(ushort), result.height));
            result.pitch = (int)p;

            result.hostData = new ushort[result.height * result.width];
            for (int j = 0; j < result.height; ++j)
            {
                for (int i = 0; i < result.width; ++i)
                {
                    result.hostData[j * result.width + i] = rawData[j * result.width + i];
                }
            }

            var handle = GCHandle.Alloc(result.hostData, GCHandleType.Pinned);
            cuda.ERROR_CHECK(cuda.Memcpy2DAsync(deviceData, p, handle.AddrOfPinnedObject(), result.width * sizeof(ushort), result.width * sizeof(ushort), result.height, cudaMemcpyKind.cudaMemcpyHostToDevice, stream));
            handle.Free();
            result.deviceData = deviceData;

            return result;
        }

19 Source : 04-stream-add.cs
with MIT License
from altimesh

unsafe static void Main(string[] args)
        {
            int nStreams = 8;
            cudaStream_t[] streams = new cudaStream_t[nStreams];
            
            //create streams

            int N = 1024 * 1024 * 32;
            float[] a = new float[N];
            float[] b = new float[N];

            for (int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            IntPtr d_a, d_b; // device pointers
            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);

            int slice = N / nStreams; // size of the array compute by each stream 

            dynamic wrapped = HybRunner.Cuda().Wrap(new Program());
            int start;
            int stop;
            
            // call kernel with each stream 

            // copy data device to host

            // synchronize and destroy streams

            for (int i = 0; i < N; ++i)
            {
                if (a[i] != (float)i + (1.0F * 100.0F))
                {
                    Console.Error.WriteLine("ERROR at {0} -- {1} != {2}", i, a[i], i + 1);
                    Environment.Exit(6); // abort
                }
            }

            handle_a.Free();
            handle_b.Free();
        }

19 Source : 03-surface.cs
with MIT License
from altimesh

static void Main(string[] args)
        {
            HybRunner runner = HybRunner.Cuda().SetDistrib(32, 32, 16, 16, 1, 0);
            
            GrayBitmap image = GrayBitmap.Load("../../images/lena512.bmp");
            uint height = image.Height, width = image.Width;
            ushort[] inputPixels = image.PixelsUShort;
            
            float[] imageFloat = new float[width * height];

            for (int i = 0; i < width * height; ++i)
            {
                imageFloat[i] = (float)inputPixels[i];
            }

            IntPtr src = runner.Marshaller.MarshalManagedToNative(imageFloat);

            //bind texture
            cudaChannelFormatDesc channelDescTex = TextureHelpers.cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKind.cudaChannelFormatKindFloat);
            cudaArray_t cuArrayTex = TextureHelpers.CreateCudaArray(channelDescTex, src, (int)width, (int)height);
            cudaResourceDesc resDescTex = TextureHelpers.CreateCudaResourceDesc(cuArrayTex);

            //create Texture descriptor
            cudaTextureDesc texDesc = TextureHelpers.CreateCudaTextureDesc();

            //create Texture object
            cudaTextureObject_t texObj;
            cuda.CreateTextureObject(out texObj, ref resDescTex, ref texDesc);

            //bind surface
            cudaChannelFormatDesc channelDescSurf = TextureHelpers.cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKind.cudaChannelFormatKindFloat);
            cudaArray_t cuArraySurf;
            cuda.MallocArray(out cuArraySurf, ref channelDescSurf, width, height, cudaMallocArrayFlags.cudaArraySurfaceLoadStore);

            //create cudaResourceDesc for surface
            cudaResourceDesc resDescSurf = TextureHelpers.CreateCudaResourceDesc(cuArraySurf);

            //create surface object
            cudaSurfaceObject_t surfObj;
            cuda.CreateSurfaceObject(out surfObj, ref resDescSurf);

            dynamic wrapper = runner.Wrap(new Program());

            wrapper.Sobel(texObj, surfObj, (int)width, (int)height);

            //pinned float array to allow the copy of the surface object on the host
            float[] imageCompute = new float[width * height];
            GCHandle handle = GCHandle.Alloc(imageCompute, GCHandleType.Pinned);
            IntPtr dest = handle.AddrOfPinnedObject();

            cuda.MemcpyFromArray(dest, cuArraySurf, 0, 0, width * height * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost);

            ushort[] outputPixel = new ushort[width * height];
            for (int i = 0; i < width * height; ++i)
            {
                outputPixel[i] = (ushort)imageCompute[i];
            }

            GrayBitmap imageSobel = new GrayBitmap(width, height);
            imageSobel.PixelsUShort = outputPixel;
            imageSobel.Save("../../output-3-surface/sobel.bmp");
        }

19 Source : Utils.cs
with MIT License
from altskop

public static T FromBytes<T>(byte[] bytes)
        {
            GCHandle gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            var data = (T)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(T));
            gcHandle.Free();
            return data;
        }

19 Source : NetworkClass.cs
with GNU General Public License v2.0
from AmanoTooko

private static ParseResult Parse(byte[] data)
        {
            GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
            FFXIVMessageHeader head = (FFXIVMessageHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(FFXIVMessageHeader));
            handle.Free();

            ParseResult result = new ParseResult();
            result.header = head;
            result.data = data;

            return result;
        }

19 Source : DataStream.cs
with MIT License
from amerkoleci

public static DataStream Create<T>(T[] userBuffer, bool canRead, bool canWrite, int index = 0, bool pinBuffer = true) where T : unmanaged
        {
            if (userBuffer == null)
                throw new ArgumentNullException(nameof(userBuffer));

            if (index < 0 || index > userBuffer.Length)
                throw new ArgumentException("Index is out of range [0, userBuffer.Length-1]", "index");

            int sizeOfBuffer = userBuffer.Length * sizeof(T);
            int indexOffset = index * sizeof(T);

            if (pinBuffer)
            {
                var handle = GCHandle.Alloc(userBuffer, GCHandleType.Pinned);
                return new DataStream(indexOffset + (byte*)handle.AddrOfPinnedObject(), sizeOfBuffer - indexOffset, canRead, canWrite, handle);
            }

            return new DataStream(indexOffset + (byte*)Unsafe.AsPointer(ref userBuffer[0]), sizeOfBuffer - indexOffset, canRead, canWrite, true);
        }

19 Source : PropertyAccessor.cs
with MIT License
from amerkoleci

protected unsafe void SetObject(IntPtr guid, object value)
        {
            // NOT WORKING with APPDATA
            var prop = new PropertyPointer();
            InitHeader<PropertyPointer>(ref prop.Header);
            var dataValue = IntPtr.Zero;
            prop.Data = new UIntPtr(&dataValue);

            // Free previous application data if any
            Device.GetProperty(guid, new IntPtr(&prop));

            GCHandle handle;
            if ((long)prop.Data.ToUInt64() != -1)
            {
                IntPtr ptr = unchecked((IntPtr)(long)(ulong)prop.Data);

                handle = GCHandle.FromIntPtr(ptr);
                if (handle.IsAllocated)
                    handle.Free();
            }

            // Set new object value
            handle = GCHandle.Alloc(value, GCHandleType.Pinned);
            prop.Data =  unchecked((UIntPtr)(ulong)(long)handle.AddrOfPinnedObject()) ;
            Device.SetProperty(guid, new IntPtr(&prop));
        }

19 Source : IncludeShadow.cs
with MIT License
from amerkoleci

private static Result OpenImpl(IntPtr thisPtr, IncludeType includeType, IntPtr fileNameRef, IntPtr pParentData, ref IntPtr dataRef, ref int bytesRef)
            {
                try
                {
                    IncludeShadow shadow = ToShadow<IncludeShadow>(thisPtr);
                    Include callback = (Include)shadow.Callback;

                    Stream? stream = null;
                    Stream? parentStream = null;

                    if (shadow._frames.ContainsKey(pParentData))
                    {
                        parentStream = shadow._frames[pParentData].Stream;
                    }

                    stream = callback.Open(includeType, Marshal.PtrToStringAnsi(fileNameRef), parentStream);
                    if (stream == null)
                        return Result.Fail;

                    GCHandle handle;

                    //if (stream is DataStream)
                    //{
                    //    // Magic shortcut if we happen to get a DataStream
                    //    var data = (DataStream)stream;
                    //    dataRef = data.PositionPointer;
                    //    bytesRef = (int)(data.Length - data.Position);
                    //    handle = new GCHandle();
                    //}
                    //else
                    {
                        // Read the stream into a byte array and pin it
                        byte[] data = ReadStream(stream);
                        handle = GCHandle.Alloc(data, GCHandleType.Pinned);
                        dataRef = handle.AddrOfPinnedObject();
                        bytesRef = data.Length;
                    }

                    shadow._frames.Add(dataRef, new Frame(stream, handle));

                    return Result.Ok;
                }
                catch (SharpGenException exception)
                {
                    return exception.ResultCode.Code;
                }
                catch (Exception)
                {
                    return Result.Fail;
                }
            }

19 Source : Compiler.cs
with MIT License
from amerkoleci

public static ShaderBytecode CompressShaders(params ShaderBytecode[] shaderBytecodes)
        {
            Blob? blob = default;
            var shaderData = new ShaderData[shaderBytecodes.Length];
            var handles = new GCHandle[shaderBytecodes.Length];
            try
            {
                for (int i = 0; i < shaderBytecodes.Length; i++)
                {
                    handles[i] = GCHandle.Alloc(shaderBytecodes[i].Data, GCHandleType.Pinned);

                    shaderData[i] = new ShaderData
                    {
                        BytecodePtr = handles[i].AddrOfPinnedObject(),
                        BytecodeLength = shaderBytecodes[i].Data.Length
                    };
                }
                blob = CompressShaders(shaderBytecodes.Length, shaderData, 1);
            }
            finally
            {
                foreach (var handle in handles)
                {
                    handle.Free();
                }
            }

            if (blob == null)
            {
                return default;
            }

            return new ShaderBytecode(blob);
        }

19 Source : DataFormat.cs
with MIT License
from amerkoleci

internal unsafe void __MarshalTo(ref __Native @ref)
        {
            @ref.Flags = Flags;
            @ref.DataSize = DataSize;

            @ref.ObjectArrayCount = 0;
            @ref.ObjectArrayPointer = IntPtr.Zero;

            if (ObjectsFormat != null && ObjectsFormat.Length > 0)
            {
                @ref.ObjectArrayCount = ObjectsFormat.Length;
                var nativeDataFormats = new ObjectDataFormat.__Native[ObjectsFormat.Length];
                for (int i = 0; i < ObjectsFormat.Length; i++)
                {
                    ObjectsFormat[i].__MarshalTo(ref nativeDataFormats[i]);
                }

                var handle = GCHandle.Alloc(nativeDataFormats, GCHandleType.Pinned);
                @ref.ObjectArrayPointer = handle.AddrOfPinnedObject();
            }
        }

19 Source : DataObjectFormat.cs
with MIT License
from amerkoleci

internal unsafe void __MarshalTo(ref __Native @ref)
        {
            @ref.Offset = Offset;
            @ref.Type = ((int)TypeFlags) | (((TypeFlags & DeviceObjectTypeFlags.AnyInstance) == DeviceObjectTypeFlags.AnyInstance ? 0 : InstanceNumber) << 8);
            @ref.Flags = Flags;

            if (Guid == Guid.Empty)
                @ref.GuidPointer = IntPtr.Zero;
            else
            {
                var handle = GCHandle.Alloc(Guid, GCHandleType.Pinned);
                @ref.GuidPointer = handle.AddrOfPinnedObject();
            }
        }

19 Source : AnchorDownloadRequest.cs
with MIT License
from anderm

public virtual bool GetData(byte[] data, int dataSize) {
    global::System.Runtime.InteropServices.GCHandle pinHandle_data = global::System.Runtime.InteropServices.GCHandle.Alloc(data, global::System.Runtime.InteropServices.GCHandleType.Pinned); try {
    {
      bool ret = SharingClientPINVOKE.AnchorDownloadRequest_GetData(swigCPtr, (global::System.IntPtr)pinHandle_data.AddrOfPinnedObject(), dataSize);
      return ret;
    }
    } finally { pinHandle_data.Free(); }
  }

19 Source : NetworkInMessage.cs
with MIT License
from anderm

public virtual void ReadArray(byte[] data, uint arrayLength) {
    global::System.Runtime.InteropServices.GCHandle pinHandle_data = global::System.Runtime.InteropServices.GCHandle.Alloc(data, global::System.Runtime.InteropServices.GCHandleType.Pinned); try {
    {
      SharingClientPINVOKE.NetworkInMessage_ReadArray(swigCPtr, (global::System.IntPtr)pinHandle_data.AddrOfPinnedObject(), arrayLength);
    }
    } finally { pinHandle_data.Free(); }
  }

19 Source : NetworkOutMessage.cs
with MIT License
from anderm

public virtual void WriteArray(byte[] data, uint length) {
    global::System.Runtime.InteropServices.GCHandle pinHandle_data = global::System.Runtime.InteropServices.GCHandle.Alloc(data, global::System.Runtime.InteropServices.GCHandleType.Pinned); try {
    {
      SharingClientPINVOKE.NetworkOutMessage_WriteArray(swigCPtr, (global::System.IntPtr)pinHandle_data.AddrOfPinnedObject(), length);
    }
    } finally { pinHandle_data.Free(); }
  }

19 Source : RoomManager.cs
with MIT License
from anderm

public virtual bool UploadAnchor(Room room, XString anchorName, byte[] data, int dataSize) {
    global::System.Runtime.InteropServices.GCHandle pinHandle_data = global::System.Runtime.InteropServices.GCHandle.Alloc(data, global::System.Runtime.InteropServices.GCHandleType.Pinned); try {
    {
      bool ret = SharingClientPINVOKE.RoomManager_UploadAnchor(swigCPtr, Room.getCPtr(room), XString.getCPtr(anchorName), (global::System.IntPtr)pinHandle_data.AddrOfPinnedObject(), dataSize);
      return ret;
    }
    } finally { pinHandle_data.Free(); }
  }

19 Source : XdeGuestLocator.cs
with MIT License
from anderm

private static byte[] GetStructureBytes(object obj)
        {
            var bytes = new byte[Marshal.SizeOf(obj)];

            var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false);
            handle.Free();

            return bytes;
        }

19 Source : TagImage.cs
with MIT License
from anderm

public virtual void CopyImageData(byte[] data, int bufferSize, int bytesPerPixel) {
    global::System.Runtime.InteropServices.GCHandle pinHandle_data = global::System.Runtime.InteropServices.GCHandle.Alloc(data, global::System.Runtime.InteropServices.GCHandleType.Pinned); try {
    {
      SharingClientPINVOKE.TagImage_CopyImageData(swigCPtr, (global::System.IntPtr)pinHandle_data.AddrOfPinnedObject(), bufferSize, bytesPerPixel);
    }
    } finally { pinHandle_data.Free(); }
  }

19 Source : VisualPairConnector.cs
with MIT License
from anderm

public virtual bool ProcessImage(byte[] image, int width, int height, int bytesPerPixel) {
    global::System.Runtime.InteropServices.GCHandle pinHandle_image = global::System.Runtime.InteropServices.GCHandle.Alloc(image, global::System.Runtime.InteropServices.GCHandleType.Pinned); try {
    {
      bool ret = SharingClientPINVOKE.VisualPairConnector_ProcessImage(swigCPtr, (global::System.IntPtr)pinHandle_image.AddrOfPinnedObject(), width, height, bytesPerPixel);
      return ret;
    }
    } finally { pinHandle_image.Free(); }
  }

19 Source : SpatialUnderstandingDll.cs
with MIT License
from anderm

public IntPtr PinObject(System.Object obj)
        {
            GCHandle h = GCHandle.Alloc(obj, GCHandleType.Pinned);
            reusedPinnedMemoryHandles.Add(h);
            return h.AddrOfPinnedObject();
        }

19 Source : PlaneFinding.cs
with MIT License
from anderm

private static IntPtr PinObject(System.Object obj)
        {
            GCHandle h = GCHandle.Alloc(obj, GCHandleType.Pinned);
            reusedPinnedMemoryHandles.Add(h);
            return h.AddrOfPinnedObject();
        }

19 Source : SpatialUnderstandingDll.cs
with MIT License
from anderm

public IntPtr PinString(string str)
        {
            byte[] obj = System.Text.Encoding.ASCII.GetBytes(str);
            GCHandle h = GCHandle.Alloc(obj, GCHandleType.Pinned);
            reusedPinnedMemoryHandles.Add(h);
            return h.AddrOfPinnedObject();
        }

See More Examples