简体   繁体   English

C# PInvoke C++ function 如果结构未初始化,则按值返回结构崩溃

[英]C# PInvoke of C++ function that returns struct by value crashes if the struct is left uninitialized

In this post they use a bool which can have variable size between platforms.这篇文章中,他们使用了一个可以在平台之间具有可变大小的布尔值。 No such thing is going on here.这里没有发生这样的事情。 The struct is blittable.该结构是 blittable。

The method crashes on return if the struct is left uninitialized - I'm not sure why.如果结构未初始化,则该方法在返回时崩溃 - 我不知道为什么。 Suppose I wanted to return a struct with random content.假设我想返回一个包含随机内容的结构。 Is it simply that this is invalid C++?仅仅是因为这是无效的 C++ 吗?

C++: C++:

struct H { uint32_t x; };

extern "C" __declspec(dllexport) H _cdecl GetH() {
  std::cout << "get-h called" << std::endl;
  H h{5}; // works if this is used
  // H h; // fails if this is used
  return h;
}

C#: C#:

[StructLayout(LayoutKind.Sequential)]
public struct H {
  [MarshalAs(UnmanagedType.U4)]
  public UInt32 X;
}

[DllImport("mydll.dll", EntryPoint = "GetH", CallingConvention = CallingConvention.Cdecl)]
private static extern H GetH();

void Test() { 
  H h = GetH();
  Console.WriteLine(h.X);
}

Output without initializer h{5}: Output 没有初始化器 h{5}:

  get-h called
  Test.exe exited with code -2147483645

The problem was that the code was compiled debug-mode and runtime checks for (lack of) variable initialization were setting a breakpoint.问题是代码是在调试模式下编译的,并且对(缺少)变量初始化的运行时检查设置了一个断点。 Since this was P-invoked and I was attached to the calling C#, I couldn't see what was going on in the C++ and it was simply exiting with error code 0x80000003, as @HansPassant points out.由于这是 P 调用的,并且我附加到调用 C#,我看不到 C++ 中发生了什么,它只是以错误代码 0x80000003 退出,正如@HansPassant 指出的那样。 Once I enabled native code debugging in Visual Studio, the exception became clear and the process no longer terminated abruptly.在 Visual Studio 中启用本机代码调试后,异常变得清晰,进程不再突然终止。

Also, release-mode compilation takes out the runtime checks (/RTC compile flag) and this wouldn't be an issue in release mode.此外,发布模式编译去掉了运行时检查(/RTC 编译标志),这在发布模式下不会成为问题。 So return of an uninitialized struct actually does work in practice.因此,未初始化的结构的返回实际上在实践中确实有效。

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

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