将byte []转换为SAFEARRAY

时间:2017-03-03 15:08:49

标签: c# arrays pointers pinvoke

我有一个问题,我希望有人可以提供帮助。以下代码用于在VS2012中编译:

STDMETHODIMP CGatherStore::GetPathBmp(ULONGLONG sessionID, LONG *pWidth, LONG *pHeight, SAFEARRAY **pData)
{
  m_dbOps.OpenDatabase(m_depository);
  if (m_dbOps.HasPath(sessionID))
  {
    SessionData sd(m_dbOps.GetSessionPath(sessionID));

    *pWidth  = sd.pathHeader.bcWidth;
    *pHeight = sd.pathHeader.bcHeight;

    CComSafeArray<BYTE> bmpArray;
    CComSafeArrayBound  bounds;

    *pData = SafeArrayCreate(VT_UI1, 1, &bounds);
    if (sd.spPathRawData.m_p != NULL)
    {
      bmpArray.Attach(*pData);
      bmpArray.Add(sd.GetPathSize(), reinterpret_cast<BYTE *>(sd.spPathRawData.m_p), true);
      bmpArray.Detach();
    }
  }
  else
  {
    CComSafeArrayBound bounds;

    *pData = SafeArrayCreate(VT_UI1, 1, &bounds);
  }

  return S_OK;
}

导出的声明如下:

void GetPathBmp(ulong sessionid, out int pWidth, out int pHeight, out Array pData);

调用它的函数如下:

public WriteableBitmap GetBitmapPath(ulong sessionID)
{
  WriteableBitmap bmp = null;

  try
  {
    int    width;
    int    height;
    byte[] data;

    gs.GetPathBmp(sessionID, out width, out height, out data);
    bmp = BitmapFactory.New(width, height);
    bmp.FromByteArray(data);
  }
  catch (Exception e)
  {
    System.Diagnostics.Trace.WriteLine(String.Format("GetBitmapPath failed, session ID {0} - {1}", sessionID, e.Message));
  }

  return bmp;
}

但是当我尝试在VS2015中编译它时,我收到以下错误消息:

error CS1503: Argument 4: cannot convert from 'out byte[]' to 'out System.Array'

那么如何将变量从byte []转换为SAFEARRAY。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我修改了调用函数,如下所示:

public WriteableBitmap GetBitmapPath(ulong sessionID)
{
  WriteableBitmap bmp = null;
  try
  {
    int          width;
    int          height;
    System.Array sa;

    gs.GetPathBmp(sessionID, out width, out height, out sa);
    bmp = BitmapFactory.New(width, height);

    byte[] data = new byte[sa.Length];
    sa.CopyTo(data, 0);
    bmp.FromByteArray(data);
  }
  catch (Exception e)
  {
    System.Diagnostics.Trace.WriteLine(String.Format("GetBitmapPath failed, session ID {0} - {1}", sessionID, e.Message));
  }
  return bmp;
}

似乎有效。感谢大家的帮助。