You are here:

C++/how to use class function where 'c' calling convention is required

Advertisement


Question
Let me explain by taking an example ::

i have  a class say MyClass as below
class MyClass
{
 public :
 void* ThreadFunc (void* arg);
};

i create a thread using
  pthread_create ( tid, NULL, Thread Function, NULL);
For the Thread Function i want to use the MyClass::ThreadFunc.

Thread Function has to be a 'C' Function.
So, if there a way to have MyClass::ThreadFunc used ?

Regards
harshad

-------------------------
Followup To
Question -
Hi Dharmender,
Thanks for the response.
This works fine so long as the C++ function is not a member function of a class. What if i want the member function of a class to be used at places
where 'C' functions are expected ?
I tried to enclose the class member function within the extern'C', but that gives a compiler error.
Regards
harshad
-------------------------
Followup To
Question -
hi,
pthread_create call takes the third parameter as a function that will be used as the thread function. This function needs to be a 'C' function.

If i want to use a C++ function ( function declared in a class ) in pthread_create as the thread function, how do i do it ?
I tried without success with declaring it as extern "C".
Answer -
Hi Harshad,
  Please go through the following faq for this issue:
http://users.utu.fi/~sisasa/oasis/cppfaq/mixing-c-and-cpp.html#[29.6]


Regards,
RaiD
Answer -
Hi,
 Are you trying to call the member function without the object of the class? Well, that would give compiler error. In a C++ function f1(which could be used by C function f2, please use the class object obj to invoke member function m1.

Please do let me know  if there is any issue.

Thanks,
RaiD

Answer
Hi,
 Please try the same extern C (call the function in your class)

# include <stdio.h>

int func1 (void)
{
  printf ("Hello Func1\n");
  return 0;
}

======

# include <iostream>

using namespace std;
extern "C"  {
  int func1 (void);
}

class help {
  int x;
public :
  void myfunc(void) {
     x = func1();
     cout << "x is " << x << endl;
  }
  help() {x = 1;}
};


int main ()
{
  
  help obj;
  obj.myfunc();
  return 0;
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Dharmender Rai

Expertise

I can answer general and system level C/C++ questions.

Experience

I have 5 years of experience in C++.

©2016 About.com. All rights reserved.