2009-09-10 103 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; 
}