我有一个用非托管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)
答案 0 :(得分:0)
不要做
p2.DrawIntoBuffer(ref buf[X * Y * 32 / 8], X, Y);
因为这是在数组之后向内存发送引用(指针)。
待办事项
p2.DrawIntoBuffer(ref buf[0], X, Y);
这会将引用(指针)发送到数组中的第一个元素。