C++/CLI:为什么在这种情况下没有托管->非托管转换?
假设我有一个使用 /clr 开关编译的 C++/CLI 程序集。在该程序集中,有托管类调用同一程序集中定义的非托管(普通 C++)类。当您使用 Visual Studio 进行调试并查看调用堆栈时,它会显示托管->非托管和非托管->托管转换发生的位置。
那么,是什么引起了我的注意:当托管类之一从同一程序集中调用非托管类之一时,为什么没有托管/非托管转换?这些非托管类是否在幕后以某种方式转变为托管类?
Let's say I have a C++/CLI assembly compiled with the /clr switch. In that assembly, there are managed classes which call unmanaged (plain C++) classes defined in the same assembly. When you are debugging using Visual Studio, and you look at the call stack, it shows you where Managed->Unmanaged and Unmanaged->Managed transitions happen.
So, what caught my eye: Why is there no Managed/Unmanaged transition when one of the managed classes calls one of the unmanaged classes from the same assembly? Are those unmanaged classes somehow turned into managed classes behind the scenes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能是因为您没有告诉编译器您希望将“非托管代码”编译为机器代码。当 /clr 生效时,所有代码都会编译为 IL。它与标准 C++ 代码没有任何问题,只是不支持少数语言结构。
如果您将代码混合在源代码文件中,则可以使用 #pragma 进行切换:
如果您 #include 任何包含非托管代码声明的标头,您也将需要它。
Probably because you didn't tell the compiler that you wanted the 'unmanaged code' to compile to machine code. With /clr in effect, all code gets compiled to IL. It has no trouble with standard C++ code, there are just a few language constructs that are not supported.
If you mixed the code in a source code file then you can use a #pragma to switch:
You'll need this too if you #include any headers that contain unmanaged code declarations.
它们不会被编译为托管类型,但如果它们定义的源文件是使用
/clr
编译且没有#pragma unmanaged,那么它们会被编译为 IL,而不是正确的本机代码
或#pragma Managed (off)
存在。就我个人而言,我很少使用
/clr
编译整个项目,更喜欢仅在需要它的特定源文件上使用/clr
,以便将非托管类型和函数编译为正确的本机代码。They're not compiled as managed types, but they are compiled down to IL rather than proper native code if the source files they're defined in are compiled with
/clr
and no#pragma unmanaged
or#pragma managed (off)
is present.Personally, I rarely compile entire projects with
/clr
, preferring to use/clr
only on the specific source files that need it, so that unmanaged types and functions do get compiled to proper native code.