将托管引用传递给采用非托管指针的方法
有可能使这项工作成功吗?
template<class T>
fun(T * t) { t->someMemberFunc(); }
...代码中的某处:
ManagedType ^ managedP = gcnew ManagedType();
UnmanagedType * unmanagedP = new UnmanagedType();
fun(managedP);
Is it possible to make this work?
template<class T>
fun(T * t) { t->someMemberFunc(); }
... somewhere in the code:
ManagedType ^ managedP = gcnew ManagedType();
UnmanagedType * unmanagedP = new UnmanagedType();
fun(managedP);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法获取托管对象的地址。垃圾收集器可以在内存中移动它,从而随时使指针值无效。至少您必须先固定该对象。由于我无法想出有效的语法,仅仅为了进行方法调用而固定是不可取的。您需要将参数声明为跟踪句柄:
You can't take the address of a managed object. The garbage collector can move it around in memory, invalidating the pointer value at any time. At a minimum you would have to pin the object first. Short from me not being able to come up with a valid syntax, pinning just to make a method call cannot be desirable. You'll need to declare the argument as a tracking handle:
这可能与您的问题无关,但 GCHandle 和 gcroot 可能有用;它们允许您获取一个非托管对象,其中将托管对象的句柄封装在其中:
This may be unrelated to your question, but GCHandle and gcroot may be useful; they allow you to get an unmanaged object encapsulating the handle to a managed object inside: