Error in C++/CLI, Can't take address of function unless creating delegate instance using Pthread

前端 未结 2 423
囚心锁ツ
囚心锁ツ 2021-01-24 00:09

I\'m using C++/CLI on Visual C++ 2008 Professional, and since I\'m using Windows Forms that means I have managed code and I\'m trying to call the static function LoginAccounts,

2条回答
  •  醉梦人生
    2021-01-24 00:24

    There's just no point in using pthreads if all you want to do is call managed code. Use the System::Threading::Thread class instead. You still need to create the delegate that the error message is complaining about, delegates are the managed equivalent of a function pointer. With bells on, they don't just store the function address but also wrap the object pointer. Make the code look similar to this:

    using namespace System::Threading;
    ...
    private: 
        void LoginAccounts() {
            // etc...
        }
        System::Void testing_Click(System::Object^  sender, System::EventArgs^  e) {
            ThreadStart^ start = gcnew ThreadStart(this, &Form1::LoginAccounts);
            Thread^ t = gcnew Thread(start);
            t->Start();
        }
    

    Note how LoginAccounts() is an instance method here, no need to do the hokeypokey with the this reference.

    If you really, really want to use pthreads then use Marshal::GetFunctionPointerForDelegate() to convert the delegate to a pointer that you can pass to native code. Watch out, you have to keep the delegate object referenced yourself. The garbage collector cannot see references held by native code. And you still can't pass this without pinning. These are very ugly details that you can avoid by simply using the Thread class instead.

提交回复
热议问题