C# 布尔数组、COM 互操作和访问冲突
我有一个用 C++ 编写的 COM 组件。其中一个 MIDL 接口的函数定义如下:
HRESULT __stdcall GetValues(
int length,
[ref, size_is(*length)] VARIANT_BOOL out[]);
GetValues
只是用值填充 out
数组:
for (int i = 0; i < length; ++i)
out[i] = (i % 2) != 0;
我尝试使用以下命令从 C# 调用它
private bool[] mValues = new bool[100];
...
myComObject.GetValues(100, ref this.mValues[0]);
:出现访问冲突错误。我认为 C++ 将 bool 解释为 2 字节值,而在 C# 中它们仅分配为 1 字节值。
我看过 布尔类型的默认封送处理,但我没有确定如何将其应用于我的情况。 MarshalAs
属性似乎没有改变任何东西。我不确定如何使用它通过引用传递数组?
[MarshalAs(UnmanagedType.U1)]
private bool[] mValues = new bool[100];
I have a COM component written in C++. One of the MIDL interfaces has a function defined like:
HRESULT __stdcall GetValues(
int length,
[ref, size_is(*length)] VARIANT_BOOL out[]);
GetValues
just populates the out
array with values:
for (int i = 0; i < length; ++i)
out[i] = (i % 2) != 0;
I've tried to call it from C# using the following:
private bool[] mValues = new bool[100];
...
myComObject.GetValues(100, ref this.mValues[0]);
I'm getting access violation errors. I think the C++ is interpreting the bool
s as 2-byte values, whereas in C# they're only allocated as 1-byte values.
I've looked at Default Marshaling for Boolean Types but I'm not sure how to apply that to my situation. The MarshalAs
attribute doesn't seem to change anything. I'm not sure how to use it for passing an array by reference?
[MarshalAs(UnmanagedType.U1)]
private bool[] mValues = new bool[100];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
VARIANT_BOOL
确实是一个 2 字节值:http://blogs.msdn.com/b/oldnewthing/archive/2004/12/22/329884.aspx所以当如果您将其编组为
UnmanagedType.VariantBool
,则不会更改任何内容,因为您将其编组为与返回的内容完全相同的内容。我首先尝试的是
UnmanagementType.U1
。如果这不起作用,我会尝试使用short[]
而不是bool[]
。VARIANT_BOOL
is indeed a 2-byte value: http://blogs.msdn.com/b/oldnewthing/archive/2004/12/22/329884.aspxSo when you marshal it as
UnmanagedType.VariantBool
, you're not changing anything because you're marshalling it in as exactly the same thing that's being returned anyway.What I would try first is
UnmanagedType.U1
. If that doesn't work, I would try to ashort[]
instead ofbool[]
.