混合托管和非托管C ++代码? [英] Mixing managed and unmanaged C++ code?

查看:242
本文介绍了混合托管和非托管C ++代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些关于混合托管C ++和非托管C ++的具体问题:

I have a couple specific questions regarding mixing managed C++ with unmanaged C++:


  1. 如果我省略 ref value 在类/结构声明中,是否自动使类/结构非托管?或者我还需要包括 #pragma unmanaged #pragma managed 指令吗?

  2. 非托管和托管类型的兼容性如何?例如,我可以在托管类中有一个非托管对象,对吧?我可以传递一个非托管的类/结构到一个托管函数(即传递一个std ::字符串到托管函数)?

  1. If I leave out ref and value in a class/struct declaration, does that automatically make the class/struct unmanaged? Or do I still need to include the #pragma unmanaged and #pragma managed directives?
  2. How compatible are unmanaged and managed types? For example, I can have an unmanaged object in a managed class, right? Can I pass an unmanaged class/struct to a managed function (ie. pass a std::string to a managed function)?

感谢您的帮助,

Alex

推荐答案

有混合类型(包含受管对象的本地类,反之亦然)。可能的是在一个托管的类中有一个指向一个本地类的指针,一个托管句柄用一个本地类中的 gcroot 模板包装。这需要确保垃圾收集器从不尝试移动原生数据(这将破坏纯本地代码所持有的指针)。

You can't have hybrid types (native class containing a managed object, or vice versa). What is possible is to have a pointer to a native class inside a managed one, and a managed handle, wrapped with the gcroot template, inside a native class. This is needed to make sure that the garbage collector never tries to move native data around (which would break pointers held by pure native code).

托管类型总是使用托管代码。

Managed types are always implemented using managed code. Native types must be implemented using managed code if they call to managed types.

#pragma managed(push,off)是强制代码编译为本机的方式。这样做的几个原因:从C ++编译器更好的优化,不能被垃圾收集等中断。或者,您可以使用 / clr:pure 强制所有代码编译为托管,甚至 / clr:safe 来做同样的事情,并使它可以验证。

#pragma managed(push, off) is the way to force code to be compiled as native. A couple reasons to do this: better optimization from the C++ compiler, can't be interrupted by garbage collection, etc. Alternatively, you can use /clr:pure to force all code to be compiled as managed, or even /clr:safe to do the same thing and also make it verifiable.

编译为托管的任何代码都可以接受本机类型和托管类型作为参数和返回值。该代码可以在托管类型,本机类型或自由(全局)函数内。

Any code that is compiled as managed can accept both native and managed types as arguments and return values. And that code can be inside a managed type, native type, or free (global) function.

这篇关于混合托管和非托管C ++代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆