C# 布尔数组、COM 互操作和访问冲突

发布于 2024-11-14 16:06:43 字数 803 浏览 9 评论 0原文

我有一个用 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 bools 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小姐丶请自重 2024-11-21 16:06:43

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.aspx

So 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 a short[] instead of bool[].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文