CFStringGetCharacters in Unity5.0 crash?

What was changed in U5.0???

The code was working in version U4.6 and when I update to U5.0.0.0f4:

Receiving unhandled NULL exception
Launching bug reporter
Obtained 46 stack frames.
#0 0x007fff90e866d0 in __CFStrConvertBytesToUnicode
#1 0x0000012f73c09e in (wrapper managed-to-native) ws.winx.platform.osx.Native:CFStringGetCharacters (intptr,ws.winx.platform.osx.Native/CFRange,intptr) + 0x10e (0x12f73bf90 0x12f73c0ea) [0x10d646330 - Unity Child Domain]
#2 0x0000012f73bacb in ws.winx.platform.osx.Native/CFString:ToString () + 0x23b (0x12f73b890 0x12f73bc63) [0x10d646330 - Unity Child Domain]
#3 0x0000012f739053 in ws.winx.platform.osx.OSXHIDInterface:HidDeviceAdded

In Above function

public override string ToString ()
			{
				if(base.Value==null){
				if (typeRef == IntPtr.Zero)
					return null;
				
				string str;
				int length = CFStringGetLength(typeRef);        
				IntPtr u = CFStringGetCharactersPtr(typeRef);
				IntPtr buffer = IntPtr.Zero;
				if (u == IntPtr.Zero)
				{
					CFRange range = new CFRange(0, length);
					buffer = Marshal.AllocCoTaskMem(length * 2);
				--->	CFStringGetCharacters(typeRef, range, buffer);
					u = buffer;
				}
				unsafe
				{
					str = new string((char*)u, 0, length);
				}
				if (buffer != IntPtr.Zero)
					Marshal.FreeCoTaskMem(buffer);
					base.Value=str;
					return base.Value as String;
				}else 
					return base.Value as String;
			}

I have been looking into this my self and it seems the crash is due to the fact that the supplied CFRange is expected to have it’s “Length” and “Location” members defined as signed longs.

internal struct CFRange
{
    public long Location;
    public long Length;
    
    public CFRange(long l, long len)
    {
        Location = l;
        Length = len;
    }
}

This requires a couple of spots, like “CFStringGetLength” or “LSGetApplicationForURL”, etc. to return a long instead of an int.

And of course when making the new string, casting the long as an int (for safety you should check it for overflow first).

Thx a lot. @iFischer_d It’s really hard to develop for OSX cos of lack of docs. To develop using C# is even harder. And string manipulation from C++ to C# is one of the energy black holes.