Search Unity

DLL UINT array pointer

Discussion in 'Scripting' started by ElmarKleijn, Aug 24, 2009.

  1. ElmarKleijn

    ElmarKleijn

    Joined:
    May 11, 2009
    Posts:
    87
    Hey everyone,

    I was just trying to use an external DLL developed in flat assembly. I got everything nicely imported, except I am stuck on the "UINT pointer to an array of floats:

    original:

    UINT GetData(
    UINT ptrFloatArray);

    my version:

    [DllImport ("dll")]
    private static extern uint GetData( uint ptrFloatArray );


    I have tried a lot the last couple of hours, but Unity keeps crashing (and I am totally the one to blame for that! ;)).

    Most of the time I have been trying to use the GCHandle in various ways:

    Code (csharp):
    1.  
    2.     private GCHandle _hGCFile;
    3.     public float[] buffer;
    4.  
    5.         // get the legth of the file
    6.         uint length = 512;
    7.        
    8.         // create the buffer which will keep the file in memory
    9.         buffer = new float[length];
    10.  
    11.         _hGCFile = GCHandle.Alloc( buffer, GCHandleType.Pinned );
    12.  
    and then using GCHandle.ToIntPtr(_hGCFile) as parameter, or other variants including casts to uint, UInt32, Int32, etc. Or just passing the array as float[] to the function.

    But nothing works, and if Unity does not crash, the array stays empty (which is not good as well ;)). Anyone have a simple suggestion on what I might be overlooking?

    Thanks!
     
  2. cyb3rmaniak

    cyb3rmaniak

    Joined:
    Dec 10, 2007
    Posts:
    162
    The TexturePlugin example helped me out a lot.

    It's pretty much exactly what you want.
    They parse Unity's Color (which is made of four floats) - so just take is as a reference and edit as needed.
     
  3. perlohmann

    perlohmann

    Joined:
    Feb 12, 2009
    Posts:
    221
    This is a small snippet of some dll interface code I wrote. Maybe you can get some hints to your problem from that.

    Code (csharp):
    1.  
    2. static extern int VcGetEncBytes(IntPtr pData, int maxLength, IntPtr pWrittenBytes);
    3.  
    4.  
    5. public static bool GetEncodedBytes(ref byte[] array, ref int writtenBytes)
    6. {
    7.     GCHandle pArray = GCHandle.Alloc(array, GCHandleType.Pinned);
    8.     GCHandle pWrittenBytes = GCHandle.Alloc(writtenBytes, GCHandleType.Pinned);
    9.     if (VcGetEncBytes(pArray.AddrOfPinnedObject(), array.Length*sizeof(byte), pWrittenBytes.AddrOfPinnedObject()) == (int)VoiceComponentReturn.Success)
    10.     {
    11.         writtenBytes = (int)pWrittenBytes.Target;
    12.         pArray.Free();
    13.         pWrittenBytes.Free();
    14.         return true;
    15.     }
    16.     writtenBytes = 0;
    17.     pArray.Free();
    18.     pWrittenBytes.Free();
    19.     return false;
    20. }
    21.  
    //perlohmann