Rub*_*oso 3 winapi pointers managed-c++ c++-cli
我有一个通过委托调用的回调。在其中,我需要处理从记录过程到达的缓冲区数据。通常,在非托管上下文中,我可以对 dwParam1 执行reinterpret_cast 来获取对象引用。但在托管上下文中,如何将 DWORD_PTR 转换为托管对象引用?
static void WaveInProc(HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
{
ControlLib::SoundDevice^ soudDevice = ?cast_native2managed?(dwParam1);
Run Code Online (Sandbox Code Playgroud)
在这里,或多或少 gcroot (根据我上面的评论)所做的:
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);
}
}
Run Code Online (Sandbox Code Playgroud)