简体   繁体   English

通过 PInvoke 从 C# 到 C++ 的简单结构中的垃圾数据

[英]Garbage data in simple struct from C# to C++ via PInvoke

I have a simple Size struct which is defined as我有一个简单的 Size 结构,它被定义为

#pragma pack(push, 8)
struct Size final
{
public:
  std::int32_t Width = 0;
  std::int32_t Height = 0;
};
#pragma pack(pop)

In C++ and as在 C++ 和作为

[StructLayout(LayoutKind.Sequential, Pack = 8)]
public class Size
{
    public System.Int32 Width { get; set; }
    public System.Int32 Height { get; set; }
}

In C#.在 C# 中。

Now, I'm trying to create a C# Size object and send it to the C++ code, for that I have this function in C++现在,我正在尝试创建一个 C# Size 对象并将其发送到 C++ 代码,为此我在 C++ 中有这个函数

extern "C" {
__declspec(dllexport) auto Test(Common::Size size) -> void;
}

auto Test(const Common::Size size) -> void
{
    // Do something
}

and a PInvoke C# function to call it as:和一个 PInvoke C# 函数来调用它:

[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Test")]
public static extern void Test(Common.Size size);

To wrap it up, I do call the Test function with this code:总结一下,我确实使用以下代码调用了 Test 函数:

var outputSize = new Common.Size() { Width = 100, Height = 200 };
PluginApi.Test(outputSize);

Now, what I would expect is to the parameter size in the C++ function to have the values 100 and 200 to Width and Height respectively, but what I get is garbage number, to be more exact, 132313736 for Width and 0 to Height.现在,我期望 C++ 函数中的参数大小分别为宽度和高度的值分别为 100 和 200,但我得到的是垃圾数,更准确地说,宽度为 132313736,宽度为 0 到高度。

What I'm doing wrong in this case?在这种情况下我做错了什么?

It has to do with public class Size in C#, which may introduce a "header" for each object holding, for example, type information (a "vtable pointer" if you want).它与 C# 中的public class Size有关,它可能会为每个保存的对象引入一个“头”,例如,类型信息(如果需要,可以使用“vtable 指针”)。 So the memory layout of an object in c# and an instance of the struct in C++ will probably not match.因此,c# 中对象的内存布局和 C++ 中结构的实例可能不匹配。

Using a struct in C# instead of a class should solve the problem.在 C# 中使用结构而不是类应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM