如何使用REF类从C++中的线程中访问非静态方法
我想从.net调用一个类。我把班级装饰成“裁判”。我有一个非静态方法“someFunc”,我计划使用线程调用它 //在A.h中,我有以下代码如何使用REF类从C++中的线程中访问非静态方法,c++,multithreading,c++-cli,C++,Multithreading,C++ Cli,我想从.net调用一个类。我把班级装饰成“裁判”。我有一个非静态方法“someFunc”,我计划使用线程调用它 //在A.h中,我有以下代码 include "afxwin.h" include "msclr\auto_gcroot.h" using namespace System; using msclr::auto_gcroot; namespace A { public ref class A { public: virtual b
include "afxwin.h"
include "msclr\auto_gcroot.h"
using namespace System;
using msclr::auto_gcroot;
namespace A
{
public ref class A
{
public:
virtual bool Func();
A();
~A();
virtual bool Connect();
protected:
DWORD WINAPI threadConnect(void* pParam);
};
public class AHelper
{
public:
auto_gcroot A;
};
}
在A.cpp中,我有以下代码
// This is the main DLL file.
include "stdafx.h"
include "A.h"
include "string"
include "sstream"
include "stdlib.h"
include "strsafe.h"
include "windows.h"
include "tchar.h"
namespace A
{
A::A()
{
m_FuncHandle = mpsNil;
}
A::~A()
{
}
bool A::Func()
{
return true;
}
bool A::Connect()
{
AHelper* AHelper;
m_retVal = false;
AHelper = new AHelper();
AHelper->A = this;
HANDLE Handle_Of_Thread = 0;
DWORD dwThreadId;
//DWORD WINAPI threadConnect(void* pParam);
//If I declare the function declaration here I am getting
//error LNK2001: unresolved external symbol "unsigned long __stdcall threadConnect(void *)" (?threadConnect@@YGKPAX@Z)
Handle_Of_Thread = CreateThread (NULL, 0, threadConnect, AHelper, 0, &dwThreadId); // with this code I am getting
//error C3867: 'A::A::threadConnect': function call missing argument list; use '&A::A::threadConnect' to create a pointer to member
return m_retVal;
}
DWORD WINAPI A::threadConnect(void* pParam)
{
AHelper* AHelper = reinterpret_cast(pParam);
//Here I need to call Func
return 0;
}
}
使用托管类型而不是非托管类型来调用托管类型上的方法
gcnew Thread(gcnew ThreadStart(this, &A::threadConnect));
并更改方法声明以匹配托管线程的预期签名
void A::threadConnect()
{
// No need for AHelper. The thread that's running will have a reference to
// the 'this' object, so no need for a GCRoot to keep it alive.
}
REF类意味着它是C++类/Cyrf类,是类,在C++中是等价的类。C++标准的可能的复制不支持REF类。C是一种在.Net CLR公共语言运行库上运行的.Net语言。C++/CLI是微软开发C++ C++语言和.NET语言的语言,它使用C++类的语法。CLI表示公共语言接口。这就是你正在使用的