c# - 将结构数组从 .NET 编码到 C++ : when does it do copying?

标签 c# .net performance pinvoke marshalling

考虑像 System.Drawing.Point 这样的结构 - 一个具有 LayoutKind.Sequential 且仅包含原始成员的结构。我有一个此类结构的 C# 数组。

我通过 P/Invoke 将它传递给一个(非托管的)C++ 函数。在 C++ 方面,有相应的结构定义(例如 struct Point { int x, y; };)。该函数采用 Point* 参数。

我的问题是,在什么情况下 CLR 会复制数据,在什么情况下它只是固定数据?变量包括:

  • 数组类型:一维或矩形
  • 函数的 C# 定义 - 使用 Point*Point[]/Point[,]
  • 是否使用fixed(Point* pointer = array)

我想避免复制,因为它很慢。

最佳答案

我在固定方面没有太多经验,但是,根据我对 MSDN 的阅读,您的结构应该固定而不是复制。相关引用:

  1. Marshalling data with PInvoke
  2. Copying and pinning
  3. Blittable and non-blittable types
  4. Default marshalling for value types

来自#2:

Formatted blittable classes have fixed layout (formatted) and common data representation in both managed and unmanaged memory. When these types require marshaling, a pointer to the object in the heap is passed to the callee directly.

并且您的 Point 结构在#3 中作为示例给出,因此它符合 blittable 类型的条件。

我注意到固定对象有一些开销 here ,但那是针对 fixed byte[] 的,它可能与您的 Point[] 不同。

关于c# - 将结构数组从 .NET 编码到 C++ : when does it do copying?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8529389/

相关文章:

java - java 32 位和 64 位之间的空循环存在巨大的性能差异

c# - 带约束的 Moq 表达式 ... It.Is<Expression<Func<T, bool>>>

c# - 在 C# 中出现 SQL 语法错误

c# - 用于删除所有字符串重复并分配给数组的正则表达式

performance - 标记扫描GC怎么了?

performance - 简单的代码加速

c# - transactionscope 锁定表

c# - 代码没有错误,但是从数据库中检索到的数据没有显示在列表框中

.net - 使用 NetTcpBinding 通过 WCF 流式传输

c# - 使用 BouncyCaSTLe 加密私钥