multithreading - 使用 win32 线程的 C++/CLI 引用类

标签 multithreading interop c++-cli

我正在尝试将一些较旧的 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/

相关文章:

java - 如何防止我的消费者线程两次删除最后一个元素?

java - 将不同语言的插件集成到一个框架中

f# - 为什么这个计量单位限制为 1?

c++ CLI Export void return __declspec(dllexport) 不能应用于具有 __clrcall 调用约定的函数

c++ - 在 C++ 中使用 vector 的多线程

.net - NOLOCK 与多线程

c# - Microsoft.Office.Interop.Excel.ApplicationClass 没有定义构造函数

c++ - Visual C++/Cli 中的异步 sleep ,如何创建一个 X 毫秒的时间来调用函数而不会使 GUI 停止

windows - C++/CLI 中的错误,除非使用 Pthread 创建委托(delegate)实例,否则无法获取函数地址

c# - 正确的线程方法