简体   繁体   中英

How do I pass a C++ reference, to a pointer argument of a C function?

I just want to check here on how to pass a reference to a function that wants a pointer. I have a code example below. In my case, I am passing a C++ reference to a C function that will change my value.

Should I use the '&' address of operator in this call: retCode=MyCFunc( &myVar)? It seems that I am taking a reference of a reference, which is not allowed in C++. However, it compiles fine and seems to work.

MainFunc()
{

    int retCode = 0;
    unsigned long myVar = 0;

    retCode = MyCPlusPlusFunc(myVar);

    // use myVars new value for some checks
    ...
    ...
}

int MyCPlusPlusFunc( unsigned long& myVar)
{
  int retCode = 0;
  retCode=MyCFunc( &myVar);
  return retCode;  
}

int MyCFunc ( unsigned long* myVar) 
{
  *myVar = 5;
}

I thought my code was above was fine, until I saw this example on the IBM site (they do not pass using the '&' address of operator): http://publib.boulder.ibm.com/infocenter/zos/v1r11/index.jsp?topic=/com.ibm.zos.r11.ceea400/ceea417020.htm

// C++ Usage
extern "C" {
  int cfunc(int *);
}

main()
{
  int result, y=5;
  int& x=y;

  result=cfunc(x); /* by reference */
  if (y==6)
  printf("It worked!\n");


// C Subroutine
cfunc( int *newval )
{
  // receive into pointer
  ++(*newval);
  return *newval;
}

In general, I know you can do the following:

int x = 0;
int &r = x;
int *p2 = &r; //assign pointer to a reference

What is the correct? Should I use the & address of operator in my call or not?

Your usage is correct, to do &myVar to get the address of it and pass to a function that wants a pointer. Taking the address-of a 'reference' is the same as taking the address of the referent.

The code you came across is wrong. There is no way you can pass a reference to a function that requires a pointer. At least, not for int .

Actually this:

int x = 0;
int &r = x;
int *p2 = &r;

puts into p2 the address of x , so it's what you need.

Use the & operator. Without it you are attempting an invalid conversion of int to int* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM