Skip to content

Instantly share code, notes, and snippets.

@OmerMor
Last active November 26, 2021 05:33
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OmerMor/1050703 to your computer and use it in GitHub Desktop.
Save OmerMor/1050703 to your computer and use it in GitHub Desktop.
A hack to temporarily view a float array as a byte array and vice versa, in O(1) - without mem copy. License: FreeBSD
/*
Copyright (c) 2013, Omer Mor
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project
*/
using System;
using System.Runtime.InteropServices;
namespace OmerMor.Utils
{
public static unsafe class FastArraySerializer
{
[StructLayout(LayoutKind.Explicit)]
private struct Union
{
[FieldOffset(0)] public byte[] bytes;
[FieldOffset(0)] public float[] floats;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct ArrayHeader
{
public UIntPtr type;
public UIntPtr length;
}
private static readonly UIntPtr BYTE_ARRAY_TYPE;
private static readonly UIntPtr FLOAT_ARRAY_TYPE;
static FastArraySerializer()
{
fixed (void* pBytes = new byte[1])
fixed (void* pFloats = new float[1])
{
BYTE_ARRAY_TYPE = getHeader(pBytes)->type;
FLOAT_ARRAY_TYPE = getHeader(pFloats)->type;
}
}
public static void AsByteArray(this float[] floats, Action<byte[]> action)
{
if (floats.handleNullOrEmptyArray(action))
return;
var union = new Union {floats = floats};
union.floats.toByteArray();
try
{
action(union.bytes);
}
finally
{
union.bytes.toFloatArray();
}
}
public static void AsFloatArray(this byte[] bytes, Action<float[]> action)
{
if (bytes.handleNullOrEmptyArray(action))
return;
var union = new Union {bytes = bytes};
union.bytes.toFloatArray();
try
{
action(union.floats);
}
finally
{
union.floats.toByteArray();
}
}
public static bool handleNullOrEmptyArray<TSrc,TDst>(this TSrc[] array, Action<TDst[]> action)
{
if (array == null)
{
action(null);
return true;
}
if (array.Length == 0)
{
action(new TDst[0]);
return true;
}
return false;
}
private static ArrayHeader* getHeader(void* pBytes)
{
return (ArrayHeader*)pBytes - 1;
}
private static void toFloatArray(this byte[] bytes)
{
fixed (void* pArray = bytes)
{
var pHeader = getHeader(pArray);
pHeader->type = FLOAT_ARRAY_TYPE;
pHeader->length = (UIntPtr)(bytes.Length / sizeof(float));
}
}
private static void toByteArray(this float[] floats)
{
fixed(void* pArray = floats)
{
var pHeader = getHeader(pArray);
pHeader->type = BYTE_ARRAY_TYPE;
pHeader->length = (UIntPtr)(floats.Length * sizeof(float));
}
}
}
}
/*
Copyright (c) 2013, Omer Mor
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project
*/
using System;
using System.Linq;
namespace OmerMor.Utils
{
public class FastArraySerializerTester
{
public static void Main()
{
Floats_to_bytes_and_vice_versa();
}
public static void Floats_to_bytes_and_vice_versa()
{
var floats = Enumerable.Range(0, 500).Select(i => (float)i).ToArray();
var floatsClone = new float[] {};
var bytes = new byte[] {};
floats.AsByteArray(arr =>
{
bytes = new byte[arr.Length];
Array.Copy(arr, bytes, arr.Length);
});
bytes.AsFloatArray(arr =>
{
floatsClone = new float[arr.Length];
Array.Copy(arr, floatsClone, arr.Length);
});
var areEqual = floats.SequenceEqual(floatsClone);
if (!areEqual)
throw new ApplicationException("Arrays do not match");
}
}
}
@mef526
Copy link

mef526 commented Oct 14, 2014

Thanks for this sample.
My VB code was using marshaling to pass arrays between managed VB and unmanaged C++. When the arrays grew larger, as big as 1E9 in length on x64 builds, I discovered that Marshaling actually copied the data and so I got a big hit in performance and memory use. I was looking for <reinterpret_cast> for managed arrays and this code was able to achieve it with FastArraySerializer and using my modification to keep the new type.

I changed the unmanaged C++ code memory allocator to use SByte[] arrays and the unmanaged code uses the allocated memory any way it pleases, typically as Doubles[].

The managed code calls unmanaged code and gets a GCHandle then can cast the array to any desired type without having to copy the data. I added the flag KeepNewType and changed the method name from AsFloatArray to ConvertArray.

OLD:

    public static void AsFloatArray(this byte[] bytes, Action<float[]> action)

NEW:

    public static void ConvertArray(this sbyte[] sbytes, Action<double[]> action, bool KeepNewType = true)
    {
        if (sbytes.handleNullOrEmptyArray(action))
            return;

        var union = new Union { sbytes = sbytes };
        union.sbytes.toDoubleArray();
        try
        {
            action(union.doubles);
        }
        finally
        {
            if (!KeepNewType)
                union.doubles.toByteArray();
        }
    }

In the action I have to have an array of doubles in module scope. So the implementation looks like this:

    Dim _ad As Double()
    Sub DblAction(ad As Double())
        _ad = ad
    End Sub

    Sub MySub()
    ...
        Try
            Dim nGch As GCHandle
            GraspLib.mmGrasp_dbTagArrayGch_Q(g_vi _
                , astrTagsData(nPtGraphNum) _
                , nGch)
            If GCHandle.ToIntPtr(nGch) <> IntPtr.Zero AndAlso nGch.IsAllocated Then
                Dim dblTarget As Action(Of Double()) = AddressOf DblAction
                Dim asb As SByte() = CType(nGch.Target, SByte())
                FastArraySerializer.ConvertArray(asb, dblTarget)
            End If
        Catch ex As Exception
            Debug.WriteLine(ex.ToString)
        End Try
    ...

I'd like to make further changes to the code so that the class FastArraySerializer is not static and that I can get the double[] or the sbyte[] from an instance. But for now this works well as a <reinterpret_cast> to allow me to change the type of an array.

@jkotas
Copy link

jkotas commented Sep 22, 2017

This hack is corrupting the internal garbage collector data structures. It will lead to intermittent crashes and data corruption. Hacking internal garbage collector data structures like this is absolutely not supported by the .NET runtime.

@HelloKitty
Copy link

HelloKitty commented Sep 23, 2017

Yes @OmerMor, @jkotas is 100% correct. I just came to warn you of the same thing since I based the idea for some of my work on this.

He knows what he is talking about!

@jkotas
Copy link

jkotas commented Sep 23, 2017

@OmerMor
Copy link
Author

OmerMor commented Jan 3, 2018

Thanks @jkotas & @HelloKitty !
I guess pinning the array for the entire span of the function would guard against this corruption.
What do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment