0

Not the actual code, but a representation:

I need to initiate a thread from one of my member functions and I do that this way:

return_val = pthread_create(&myThread, NULL, myStaticMethod, (void*)(this));

i) I pass this as an argument because static methods do not allow non-static members to be accessed, and since I have non-static methods and members to access inside the static method. Is this right? Or, are there any other alternatives?

myStaticMethod(void* args)    
{
    args->myPublicMethod(); //Is this legal and valid?

    args->myPrivateMember;   //Is this legal and valid?
}

I get an error saying void* is not a pointer to object type, and I think that args is to be typecast into an instance of type myClass.

But, how do I do that?

thenoGk
  • 33
  • 8
  • 1
    Note that it is not a good idea to pass C++ static functions to C, see [that answer](http://stackoverflow.com/questions/2068022/in-c-is-it-safe-portable-to-use-static-member-function-pointer-for-c-api-call) for example. Better to create an `extern "C"` wrapper around it. And use `reinterpret_cast` for that kind of casts. – Sergei Tachenov May 03 '15 at 05:09
  • @SergeyTachenov: I did go though that before actually posting the question. But, certain 'external forces' do prevent you from doing the right thing by sticking to what is normally, but incorrectly followed. – thenoGk May 03 '15 at 05:12
  • What on Earth could prevent you from writing a simple small `extern "C"` wrapper around a static member function? Just name it accordinly, like `MyClass_myStaticMethod()` to avoid name clashes. – Sergei Tachenov May 03 '15 at 05:34
  • 1
    This discussion is nonsense considering that C++ has its own threads that perfectly well interoperate with any function. Also, the correct cast is surely not `reinterpret_cast` when converting a `T*` to a `void*` and back, but `static_cast`. – Ulrich Eckhardt May 03 '15 at 13:09

1 Answers1

1
args->myPublicMethod(); //Is this legal and valid?

No. That is neither legal nor valid. However, you can use:

reinterpret_cast<MyClass*>(args)->myPublicMethod();

You can access a private member function of a class from a static member function. So, you can access a private member of the class using:

reinterpret_cast<MyClass*>(args)->myPrivateMember;

Another SO question and its answers discuss the pros and cons of using static_cast and reinterpret_cast. Since you are using void* as the intermediate type, you can use either of them.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270