Linked Questions
10 questions linked to/from C# performance - Using unsafe pointers instead of IntPtr and Marshal
167 votes
8 answers
116k views
Array.Copy vs Buffer.BlockCopy
Array.Copy and Buffer.BlockCopy both do the same thing, but BlockCopy is aimed at fast byte-level primitive array copying, whereas Copy is the general-purpose implementation. My question is - under ...
94 votes
10 answers
43k views
Why are memcpy() and memmove() faster than pointer increments?
I am copying N bytes from pSrc to pDest. This can be done in a single loop: for (int i = 0; i < N; i++) *pDest++ = *pSrc++ Why is this slower than memcpy or memmove? What tricks do they use to ...
29 votes
6 answers
33k views
True Unsafe Code Performance
I understand unsafe code is more appropriate to access things like the Windows API and do unsafe type castings than to write more performant code, but I would like to ask you if you have ever noticed ...
28 votes
5 answers
28k views
How do I marshal a struct that contains a variable-sized array to C#?
How do I marshal this C++ type? The ABS_DATA structure is used to associate an arbitrarily long data block with the length information. The declared length of the Data array is 1, but the actual ...
25 votes
4 answers
30k views
Marshal.PtrToStructure (and back again) and generic solution for endianness swapping
I have a system where a remote agent sends serialized structures (from an embedded C system) for me to read and store via IP/UDP. In some cases I need to send back the same structure types. I thought ...
21 votes
2 answers
36k views
C# - Convert unsafe byte* to byte[]
I have an unsafe byte* pointing to a native byte array of known length. How can I convert it to byte[]? An unsafe sbyte* pointing to a zero-terminated native string can be converted to a C# string ...
4 votes
2 answers
2k views
PInvoke style passing struct with member dynamic array of pointers
There appears to be multiple ways to do this, but the examples I've tried haven't worked for me. I read somewhere that using unsafe pointers would be the way to go for more complex structures that ...
3 votes
2 answers
586 views
Read-only array field in unsafe struct
This is the original declaration: [StructLayout(LayoutKind.Explicit, Size = 16)] public unsafe struct X { [FieldOffset(0)] public ushort a; [FieldOffset(2)] public fixed byte b[14]; }; I would ...
2 votes
1 answer
1k views
C# Struct to byte array marshalling the same way as with packed records in Delphi
I have a legacy application written in Delphi 2007 which generates byte arrays like this: command_data = packed record direction : word; name : array [0..9] of char; end; ...
0 votes
0 answers
184 views
Adding C dll function to C# application
I want to use a function written in C in C# application. The function is exported to dll file. C function code: #include <stdio.h> #include <stdlib.h> extern "C" __declspec(...