如何将IStream(C ++)转换为System :: IO :: Stream(c#),反之亦然

问题描述 投票:0回答:1

我有2个库,一个是c ++,另一个是c#。

C ++库的名称-> LibA

C#名称-> LibB

在LibA中,将有2个主要API:

  1. Serialize->序列化API将使用给定的输入生成IStream作为输出。
  2. Deserialize-> Deserialize API将IStream作为输入并反序列化流并从中获取实际数据。
#pragma once
struct GPosition
{
    double x;
    double y;
    double z;
};
struct GUnitVector
{
    double x;
    double y;
    double z;
};
struct GLine
{
    GPosition m_rootPoint;    /* Point on the line, should be in region of interest */
    GUnitVector m_direction;    /* Gradient */
    double m_start;        /* Parameter of start point, must be <= m_end */
    double m_end;          /* Parameter of end point */
};



class GraphicSerializer
{
public:

    GUID objectID;

    uint32_t aspectID;
    uint32_t controlFlag;
    vector<const GLine *> geomVector;

    void Serialize(IStream &pStream);
    void Deserialize(IStream* pStream);
};

在LibB中,将有4个API:

  1. Object GetObjectFromStream(Stream s)->将流作为输入并反序列化并返回Object
  2. PutToDB(Object A)->将给定的对象持久保存到DB
  3. Stream GetStreamFromObject(Object a)->将对象作为输入序列化并返回。
  4. Object GetFromDB(objectID)->根据ID从数据库获取对象
public class CommonBase
    {
        public Guid id { get; set; };
        public byte[] Bytes { get; set; } //contains aspect, control flag, vec<GLine>
    };

    public interface IGraphicRepository
    {
        CommonBase Get(Guid guid);
        bool Put(CommonBase graphic);
    }

    public static class GraphicStreamUtility
    {
        public static CommonBase GetCommonBaseFromStream(Stream stream);
        public static void SerializeCommonBaseToStream(CommonBase obj, Stream stream);
    }

现在,我正在编写C ++ / CLI以使用libA在libB中生成的流,反之亦然。这样我就可以持久地从数据库中检索对象。

[谁能让我知道如何将IStream转换为.Net Stream和将.Net流转换为IStream。

c# c++ stream c++-cli
1个回答
0
投票
Stream^ CGDMStreamCLI::ConvertIStreamToStream(IStream *pStream)
{
    ULARGE_INTEGER ulSize{};
    IStream_Size(pStream, &ulSize);
    size_t size = ulSize.QuadPart;
    auto buffer = std::make_unique<char[]>(size);
    ULONG numRead{};
    HRESULT hr = pStream->Read(buffer.get(), size, &numRead);

    if (FAILED(hr) || size != numRead)
    {
        throw std::exception("Failed to read the stream");
    }

    cli::array<Byte>^ byteArray = gcnew cli::array<Byte>(numRead+2);

    // convert native pointer to System::IntPtr with C-Style cast
    Marshal::Copy((IntPtr)buffer.get(), byteArray, 0, numRead);

    return gcnew System::IO::MemoryStream(byteArray);
}
© www.soinside.com 2019 - 2024. All rights reserved.