[英]Passing variable length array of bytes from C# to unmanaged C++ dll
I have a COM dll written in unmanaged C++ that I call from C#. 我有一个用非托管C ++编写的COM dll,可以从C#调用。 There is a method I call that I pass a buffer to that it then fills in. When it is fixed length it works, when it's variable length it fails with a "access outside of array bounds" error. 我称有一种方法,我将缓冲区传递给它,然后填充它。当它是固定长度时,它可以工作,当它是可变长度时,它会因“超出数组界限的访问”错误而失败。
Here is the fixed length that works: 这是有效的固定长度:
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 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++ C ++
STDMETHODIMP CPatternDraw::DrawIntoBuffer(unsigned char *buf, int width, int height)
Here is my attempt at a variable length array that fails: 这是我尝试的可变长度数组失败:
C# C#
PATTERNSLib.PatternDraw p2 = new PATTERNSLib.PatternDraw(); PATTERNSLib.PatternDraw p2 =新的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 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++ C ++
STDMETHODIMP CPatternDraw::DrawIntoBuffer(unsigned char *buf, int width, int height)
Don't do 不要做
p2.DrawIntoBuffer(ref buf[X * Y * 32 / 8], X, Y);
Since this is sending a reference (pointer) to the memory after the array. 由于这是在数组之后向内存发送引用(指针)。
Do 做
p2.DrawIntoBuffer(ref buf[0], X, Y);
This will send a reference (pointer) to the first element in the array. 这将向数组中的第一个元素发送一个引用(指针)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.