从 C# 获取本机类型大小
get native type size from c#
我使用 swig to c# 包装了一些 c++ 类。
有一些方法将类型的大小作为参数(任何类型都可以作为参数传递)。
我的问题是如何使用我的 C# 代码获取 C++ 对象的大小?
无法在运行时获取本机类型的大小 - 没有类型信息。
您可能希望从本机端传递大小,在本机端可以静态确定大小。只需将 getSize
方法添加到您的对象或其他内容即可。
与 C++ 不同,在 .NET 中获取对象的大小始终是运行时操作。 Marshal.SizeOf
calls do not get translated into compile-time constants in the same way that C++'s sizeof
operator does. At runtime, .NET would require a .NET object that it could reflect across, and that object must be defined correctly using attributes like StructLayout
.
所以你有两个选择:
- 定义 C++ 对象的 .NET 版本并使用
Marshal.SizeOf
。您不需要为任何事情使用 .NET 对象。它只是让您确定大小。当然,如果你把那个物体搞砸了,或者如果它们因为进化而变得不同步,你就会有一段糟糕的时光。
- 公开 C++ 的新方法 returns
sizeof(MyCppObject)
。这可能是更好的解决方案。
我使用 swig to c# 包装了一些 c++ 类。
有一些方法将类型的大小作为参数(任何类型都可以作为参数传递)。
我的问题是如何使用我的 C# 代码获取 C++ 对象的大小?
无法在运行时获取本机类型的大小 - 没有类型信息。
您可能希望从本机端传递大小,在本机端可以静态确定大小。只需将 getSize
方法添加到您的对象或其他内容即可。
与 C++ 不同,在 .NET 中获取对象的大小始终是运行时操作。 Marshal.SizeOf
calls do not get translated into compile-time constants in the same way that C++'s sizeof
operator does. At runtime, .NET would require a .NET object that it could reflect across, and that object must be defined correctly using attributes like StructLayout
.
所以你有两个选择:
- 定义 C++ 对象的 .NET 版本并使用
Marshal.SizeOf
。您不需要为任何事情使用 .NET 对象。它只是让您确定大小。当然,如果你把那个物体搞砸了,或者如果它们因为进化而变得不同步,你就会有一段糟糕的时光。 - 公开 C++ 的新方法 returns
sizeof(MyCppObject)
。这可能是更好的解决方案。