是否将本机指针转换为C ++ \ CLI受管对象引用? [英] Cast native pointer to a C++\CLI managed object reference?
本文介绍了是否将本机指针转换为C ++ \ CLI受管对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个通过委托调用的回调.在其中,我将需要处理来自记录过程的缓冲区数据.通常,在非托管上下文中,我可以在dwParam1上执行reinterpret_cast以获取对象引用. 但是在托管环境中,如何将DWORD_PTR强制转换为托管对象ref?
I have a callback that is called through a delegate. Inside it I will need to treat the buffer data that arrive from a record procedure. Normally in a unmanaged context I could do a reinterpret_cast on dwParam1 to get the object reference. But in a manged context how can I cast a DWORD_PTR to a managed object ref?
static void WaveInProc(HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
{
ControlLib::SoundDevice^ soudDevice = ?cast_native2managed?(dwParam1);
推荐答案
在这里,或多或少地,gcroot(根据我上面的评论)是做什么的:
Here ya go, more or less what gcroot (per my comment above) does:
using namespace System;
using namespace System::Runtime::InteropServices;
// track an object by a normal (not pinned) handle, encoded in a DWORD_PTR
DWORD_PTR ParamFromObject(Object^ obj)
{
return reinterpret_cast<DWORD_PTR>(GCHandle::ToIntPtr(GCHandle::Alloc(obj)).ToPointer());
}
static void WaveInProc(PVOID hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
{
// unwrap the encoded handle...
GCHandle h = GCHandle::FromIntPtr(IntPtr(reinterpret_cast<void*>(dwParam1)));
try
{
// and cast your object back out
SoundDevice^ x = safe_cast<SoundDevice^>(h.Target);
}
finally
{
// remember to free the handle when you're done, otherwise your object will never be collected
GCHandle::Free(h);
}
}
这篇关于是否将本机指针转换为C ++ \ CLI受管对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文