2009-09-10 107 views
2

我想在C++/CLI ref类中封装一些较旧的win32代码,以便更好地从.NET代码访问它。该类需要启动一个Win32线程并将一个指向该类的指针作为线程参数传递。代码如下所示:使用win32线程的C++/CLI ref类

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子系统的消息。我试过在interior_ptr中包装PlayThread函数指针,但编译器不会允许这样做。 此外,我试图让线程函数成为一个类方法,但编译器不允许在ref类方法上使用_stdcall修饰符。 你知道一个办法来处理这个吗?

+0

wht是一个mme子系统吗? – deostroll 2009-09-11 19:14:13

回答

3

托管类使用“句柄”而不是引用传递。您不能像处理指针那样处理托管类的句柄。你想要做的是创建一个本地帮助类,它包含托管类的句柄。然后你将一个指向本地帮助器的指针传递给线程启动函数。像这样:

#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; 
}