如何将对象数组传递给非托管代码?

发布于 2024-09-08 16:49:22 字数 172 浏览 1 评论 0原文

我试图将对象数组从 C# 传递到非托管 C++,但似乎没有任何效果。

编译器不会让我假装该数组是 IntPtr。将数组转换为 IntPtr 不起作用。我尝试传递固定数据的地址,但这也不起作用。

我只需要传递一个指向数组开头的指针,结果发现这是非常困难的。

有什么建议或链接吗?谢谢!

I'm trying to pass an array of objects from C# to unmanaged C++, and nothing seems to work.

The compiler won't let me pretend the array is an IntPtr. Casting the array to an IntPtr doesn't work. I've tried to pass the address of pinned data, but this didn't work either.

I just need to pass a pointer to the beginning of the array, and this is turning out to be incredibly difficult.

Any suggestions or links? Thanx!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

冷清清 2024-09-15 16:49:22

最终起作用的是:

  1. 传递结构数组而不是对象数组(引用)。
  2. 将“[StructLayout(LayoutKind.Sequential, Pack = 1)]”放在结构定义之前。
  3. 将“[MarshalAs(UnmanagedType.LPWStr)]”放在字符串之前(在结构定义中),以使字符串在 C++ 端显示为宽字符字符串。
  4. 为 DllImport 声明中的参数声明一个结构数组:“VariableObject[] varObj”。
  5. 在 C++ 端声明一个指向类的指针作为参数。 (C++ 类镜像 C# 结构。):“VariableObject* varObj”。

What finally worked:

  1. Passing an array of structs instead of an array of objects (references).
  2. Putting "[StructLayout(LayoutKind.Sequential, Pack = 1)]" just before the struct definition.
  3. Putting "[MarshalAs(UnmanagedType.LPWStr)]" before the string (in the struct definition) to cause the string to appear as a wide-character string on the C++ side.
  4. Declaring an array of structs for the argument in the DllImport declaration: "VariableObject[] varObj".
  5. Declaring a pointer to the class as the parameter on the C++ side. (The C++ class mirrors the C# struct.): "VariableObject* varObj".
寄居人 2024-09-15 16:49:22

可以转换为 void 指针吗?确保对象数组已固定。

Can you cast to a void pointer? Be sure the array of objects is pinned.

沉默的熊 2024-09-15 16:49:22

在 C#/托管方法签名中,使用 [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]... 标记输入参数,

[DllImport(...)]
public void DoTask
    (
        ...,
        [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] int[] results,
        ...
    );

然后像往常一样调用它。此外,在非托管代码中,您可以修改此数组。我建议您发送一个额外的 int 告诉非托管代码数组的大小是多少,以防止“数组越界”修改。

In your C#/Managed method signature, mark the input parameter with [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]...

[DllImport(...)]
public void DoTask
    (
        ...,
        [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] int[] results,
        ...
    );

Then call it as you did always. Also, inside the unmanaged code, you can modify this array. I suggest that you send in an extra int telling the unmanaged code what the size of the array is to prevent “array out of bound” modification.

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