将可变长度的字节数组从C#传递到非托管C ++ dll

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

我有一个用非托管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个回答
0
投票

不要这样做

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.