我正在尝试将一些较旧的 win32 代码封装在 C++/CLI 引用类中,以便可以更好地从 .NET 代码访问它。该类需要启动一个 Win32 线程并将指针作为线程参数传递给该类。代码看起来像这样:
ref class MmePlayer
{
int StartPlayback()
{
hPlayThread = CreateThread(NULL, 0, PlayThread, this, 0, &PlayThreadId);
}
};
static DWORD WINAPI PlayThread(LPVOID pThreadParam)
{
// Get a pointer to the object that started the thread
MmePlayer^ Me = pThreadParam;
}
该线程确实需要是 Win32 线程,因为它从 MME 子系统接收消息。我尝试将 PlayThread 函数指针包装在 Interior_ptr 中,但编译器不允许这样做。 另外,我尝试使线程函数成为类方法,但编译器不允许在 ref 类方法上使用 _stdcall 修饰符。 你知道处理这个问题的方法吗?
最佳答案
托管类使用“句柄”而不是引用来传递。您不能将托管类的句柄视为指针。您要做的是创建一个 native 帮助程序类,该类保存托管类的句柄。然后将指向 native 帮助程序的指针传递到线程启动函数中。像这样:
#include <msclr/auto_gcroot.h>
using msclr::auto_gcroot;
ref class MmePlayer;
class MmeHelper
{
auto_gcroot<MmePlayer^> myPlayer;
};
ref class MmePlayer
{
int StartPlayback()
{
myHelper = new MmeHelper();
myHelper->myPlayer = this;
hPlayThread = CreateThread(NULL, 0, PlayThread, myHelper, 0, &PlayThreadId);
}
MmeHelper * myHelper;
};
static DWORD WINAPI PlayThread(LPVOID pThreadParam)
{
// Get a pointer to the object that started the thread
MmeHelper* helper = pThreadParam;
}
关于multithreading - 使用 win32 线程的 C++/CLI 引用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1404732/