无法在非托管代码中使用托管事件/对象错误 c3265、c2811
我在 C++/CLI 项目中使用的本机 C++ 库引发事件并给我结果,
- 如果我尝试通过扩展非托管事件来处理该事件,它会说 ref 类只能扩展 ref 类。
- 然后,我尝试创建一个本机事件,但在其中包含托管对象来收集结果,但出现错误无法在非托管类中声明托管对象。
无论如何,有没有办法以我正在尝试的方式之一完成它,或者我应该声明非托管结果对象将它们填充到非托管事件中,然后编组它?
编辑:
class MyNativeListener: public NativeEventListener
{
private:
ManagedResultsObject ^_results;
public:
void onEndProcessing(ProcessingEvent *event)
{
_results.Value = event->value;
//Many more properties to capture
}
};
这就是我正在尝试的,我已经扩展了本机事件侦听器来捕获事件,但不确定如何将结果捕获到托管对象。
编辑2 在@mcdave auto_gcroot
Native C++ library that I am using in C++/CLI project raises events giving me results,
- If I try to handle the event by extending the unmanaged event, it says the ref class can only extend ref class.
- I then tried to create a native event but have manged object inside it to collect the results, but I get the error cannot declare managed object in unmanaged class.
Is there anyway to get it done in one of the ways I am trying, or should I declare unmanaged result objects fill them in unmanaged event and then Marshall it ?
Edit:
class MyNativeListener: public NativeEventListener
{
private:
ManagedResultsObject ^_results;
public:
void onEndProcessing(ProcessingEvent *event)
{
_results.Value = event->value;
//Many more properties to capture
}
};
This is what I am trying, I have extended the native event listener to capture the event, but not sure how to capture the results to a managed object.
Edit2
Found this while searching on the same line as suggested by @mcdave auto_gcroot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的本机类需要存储托管对象的句柄而不是对其的引用。您可以使用 gcroot 模板 执行此操作。如果您深入研究 gcroot 模板,您会发现它使用 GCHandle 结构,通过适当的静态转换可以将其存储为
void*
指针,因此提供了一种在本机代码中存储托管引用的方法。尝试按照以下几行扩展您的代码:
Your native class needs to store a handle to the managed object instead of a reference to it. You can do this using the gcroot template. If you dig into the gcroot template you will find it uses the GCHandle Structure, which with appropriate static casting can be stored as a
void*
pointer and so provides a means of storing managed references in native code.Try expanding your code along the following lines: