如何在C ++-CLI中创建全局句柄 [英] How to create a global handle in C++-CLI

查看:88
本文介绍了如何在C ++-CLI中创建全局句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C ++-CLI项目中使用C#类,但是Visual Studio只允许我在函数内部在局部范围内声明C#对象的句柄(^)。我唯一能正常工作的方法是声明一个指向句柄的全局指针:

I am trying to use a C# class in a C++-CLI project, but Visual Studio will only let me declare a handle (^) to a C# object in a local scope, just inside a function. The only way I got it working was declaring a global pointer to a handle:

SUTAdapter::Form1^ *ptForm1;

但是,如果我在函数内创建一个对象,并将其地址提供给全局指针:

But if then I create an object inside a function and give its address to the global pointer:

SUTAdapter::Form1^ form1;
form1 = gcnew SUTAdapter::Form1();
ptForm1 = &form1;
(*ptForm1)->incCounter(0);

当该函数退出并尝试在其他C ++-CLI函数中使用incCounter函数时,对象似乎消失了(调试器说这== null)。有没有办法在C ++-CLI中全局处理C#代码?我猜因为某些我不了解的原因而禁止使用全局句柄,但是我没有想法,我需要这样做。谢谢。

When the function exits and I try to use the incCounter function inside some other C++-CLI function, the object seems gone (debugger says this == null). Is there a way to have a global handle of a C# code in C++-CLI? I guess global handles are forbidden for some reason I don't understand but I am out of ideas and I need this done. Thank you.

编辑:

*ptForm1 = gcnew SUTAdapter::Form1();

给出空引用异常。为什么?

Gives a null reference exception. Why?

推荐答案

此限制似乎与其他基于CLR的语言一致。例如,C#没有静态的,函数范围的变量的概念。 C ++ / CLI中缺乏此类功能,这表明CLR的工作方式是-必须在类范围内定义静态对象。

This restriction seems consistent with the other CLR-based languages. C# has no concept of a static, function-scoped variable for example. The lack of such functionality in C++/CLI suggests that is the way the CLR works - static objects must be defined at the class scope.

CLR是基于对象的,因此

The CLR is object based, so this is just a case of that object-oriented nature influencing the design of languages that run on top of it.

从面向对象的角度来看,我更喜欢C#方式,这只是面向对象性质影响在其上运行的语言设计的一种情况。无论如何。

From an OO view point, I like the C# way better anyway.

这篇关于如何在C ++-CLI中创建全局句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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