将本地指针转换为C ++ \CLI手动对象引用? [英] Cast native pointer to a C++\CLI manged object reference?
本文介绍了将本地指针转换为C ++ \CLI手动对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个通过委托调用的回调。在其内部,我将需要处理从记录过程到达的缓冲区数据。 Normaly在非托管上下文中,我可以对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. Normaly 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);
推荐答案
这里ya go,或多或少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屋!
查看全文