如何在 C++/CLI 中将托管引用传递给非托管代码?
我仅使用 C++/CLI 在 VS2010 中对非托管 C++ 代码进行单元测试。我将编译器切换到 /clr 并使用静态库中的非托管代码。
我的测试类中有一个简单的 int
属性。 我想将其作为 const int & 传递给本机 C++ 中的函数。但它无法编译,我发现,这是因为你不能像那样混合引用。
有什么方法可以做到这一点,我尝试遵循并且它有效,但是有更好的方法吗?
[TestClass]
public ref class MyTestClass
{
private:
int _my_property;
public:
[TestMethod]
void MyTestMethod()
{
MyNativeClass c;
// c.SomeMethod(_my_property) this doesn't work
int i = _my__property;
c.SomeMethod(i) // this works
}
}
I'm using C++/CLI only to unit test unmanaged C++ code in VS2010. I switched the compiler to /clr and using the unmanaged code from a static library.
I have a simple int
property in my test class.
I would like to pass that as a const int &
to a function in native C++. But it can't compile and I've found out that, it's because you can't mix references like that.
What is the way to do it, I tried to following and it's working, but is there a nicer way?
[TestClass]
public ref class MyTestClass
{
private:
int _my_property;
public:
[TestMethod]
void MyTestMethod()
{
MyNativeClass c;
// c.SomeMethod(_my_property) this doesn't work
int i = _my__property;
c.SomeMethod(i) // this works
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C++ 引用实际上只是指针的语法糖。 C++ 指针指向内存中的特定点,而 CLI 引用可以由垃圾收集器自由移动。要将托管内存中对象的引用传递给非托管代码,您需要固定指针。
更多信息和示例在另一个SO问题中: 从 C++/CLI 转换指向本机 C++ 指针的指针
编辑 2
我正在删除附加信息,因为它显然是错误的(感谢 @Tergiver 和 @DeadMG 的评论)。我还在制作帖子社区维基,所以请随意添加任何其他正确的信息。
C++ references are really just syntactic sugare for pointers. A C++ pointer points to a specific point in memory, while CLI references can be freely moved around by the garbage collector. To pass a reference to an object in managed memory to unmanged code, you need to pin the pointer.
More info and sample in another SO question: Convert from C++/CLI pointer to native C++ pointer
Edit 2
I'm removing the additional information, since it is obviously wrong (thanks @Tergiver and @DeadMG for your comments). I'm also making the post community wiki, so feel free to add any additional correct information.