z/OS Language Environment Writing Interlanguage Communication Applications
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Passing data by reference between C and C++

z/OS Language Environment Writing Interlanguage Communication Applications
SA38-0684-00

In C, you can pass data by reference by passing a pointer to the item or passing the address of the item. In C++, you can pass a pointer, the address of the item, or a reference variable.

A pointer passed from C to C++ may be received as a pointer or as a reference variable, as in the following example:

Sample C usage C++ subroutine
#include <stdio.h>

main() {
  int result, y;
  int *x;

  y=5;
  x= &y;

  result=cppfunc(x);
    /* by reference */
  if (y==6)
  printf("It worked!\n");
}
#include <stdio.h>

extern "C" {
  int cppfunc(int *);
}

cppfunc(int *newval)
{     // receive into pointer
  ++(*newval);
  return *newval;
}
Sample C usage C++ subroutine
#include <stdio.h>

main() {
  int result, y;
  int *x;

  y=5;
  x= &y;

  result=cppfunc(x);
    /* by reference */
  if (y==6)
  printf("It worked!\n");
}
#include <stdio.h>

extern "C" {
  int cppfunc(int&);
}

cppfunc(int&; newval)
{  // receive into reference variable
  ++newval;
  return newval;
}

A pointer, or the address of a variable, passed from C++ to C must be received as a pointer, as in the following example:

Sample C++ usage C subroutine
#include <stdio.h>
extern "C" {
  int cfunc(int *);
}

main() {
  int result, y;
  int *x;

  y=5;
  x= &y;

  result=cfunc(x);  /* by reference */
  if (y==6)
    printf("It worked!\n");
}
#include <stdio.h>

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

Similarly, a reference variable passed from C++ to C must be received as a pointer, as in the following example:

Sample C++ usage C subroutine
#include <stdio.h>
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");
}
#include <stdio.h>

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

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014