使用win32线程的C ++ / CLI ref类

时间:2009-09-10 11:25:33

标签: multithreading interop c++-cli

我正在尝试将一些旧的win32代码封装在C ++ / CLI ref类中,以便从.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子系统的消息。我试过在Interior_ptr中包装PlayThread函数指针,但编译器不允许这样做。 此外,我试图使线程函数成为类方法,但编译器不允许在ref类方法上使用_stdcall修饰符。 你知道一种处理方法吗?

1 个答案:

答案 0 :(得分:3)

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

#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;
}
相关问题