2013-04-12 102 views
1

我有一個我想從.net調用的類。我把課堂裝飾成'ref'。我有一個非靜態方法'someFunc',我打算使用Thread來調用。如何從C++中的線程訪問非靜態方法使用ref類

//在啊,我有以下代碼

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 *)" ([email protected]@[email protected]) 

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



} 
+0

ref class表示它是C++/CLI –

+0

ref class是託管類,相當於Csharp中的類。 – user2271083

+0

[C++/cli傳遞(託管)委託給非託管代碼的可能的重複](http://stackoverflow.com/questions/2972452/c-cli-pass-managed-delegate-to-unmanaged-code) –

回答

0

使用管理thread,而不是一個非託管之一,調用一個方法在一個託管類型。

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. 
} 
相關問題