【问题标题】:Passing variable length array of bytes from C# to unmanaged C++ dll将可变长度的字节数组从 C# 传递到非托管 C++ dll
【发布时间】:2014-04-03 23:00:45
【问题描述】:

我有一个用非托管 C++ 编写的 COM dll,我从 C# 调用它。我调用了一种方法,我将缓冲区传递给它然后填充。当它是固定长度时它可以工作,当它是可变长度时它会失败并出现“访问数组边界之外”错误。

这是有效的固定长度:

C#

PATTERNSLib.PatternDraw p2 = new PATTERNSLib.PatternDraw();

Byte[] buf = new Byte[X * Y * 32 / 8];   // X=756, Y=360 in this case

p2.DrawIntoBuffer(buf, X, Y);

IDL

[id(53), helpstring("method DrawIntoBuffer")]
HRESULT DrawIntoBuffer([in, out] unsigned char buf[756*360*32/8], [in] int width, 
                        [in] int height);    // size hard coded which is a problem

C++

STDMETHODIMP CPatternDraw::DrawIntoBuffer(unsigned char *buf, int width, int height)

这是我对可变长度数组的尝试,但失败了:

C#

PATTERNSLib.PatternDraw p2 = new PATTERNSLib.PatternDraw();

Byte[] buf = new Byte[X * Y * 32 / 8];   // Goal is variable length

p2.DrawIntoBuffer(ref buf[X * Y * 32 / 8], X, Y);   // compiler error indicated ref was required

IDL

[id(53), helpstring("method DrawIntoBuffer")] 
HRESULT DrawIntoBuffer([in, size_is(width*height*32/8), out] unsigned char *buf, 
                       [in] int width, [in] int height);

C++

STDMETHODIMP CPatternDraw::DrawIntoBuffer(unsigned char *buf, int width, int height)

【问题讨论】:

    标签: c# c++ unmanaged idl


    【解决方案1】:

    别这样

    p2.DrawIntoBuffer(ref buf[X * Y * 32 / 8], X, Y); 
    

    因为这是在数组之后发送一个指向内存的引用(指针)。

    p2.DrawIntoBuffer(ref buf[0], X, Y); 
    

    这将向数组中的第一个元素发送一个引用(指针)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多