/*

by compiling the

“calling_c.C”

module must be

*/

/*

linked to create

an executable

file.

*/

/****************************************************/ #include <stdio.h>

#include “string.h” char* get_name()

{

static char name[80]; printf(“Enter the name: “); scanf(“%s”,name);

return name;

}

/****************************************************/

Running the Example

Following is a sample run of the executable file that results when you link the object modules generated by compiling calling_c.C and get_name.c:

Enter the name:Joann

Joann has a balance of 0

HP C Calling HP aC++

If you mix C++ modules with C modules, refer to “Linking Your HP aC++ Libraries with Other Languages” (page 196).

Since most C++ programs use the HP aC++ run-time libraries, you can call a C++ module from a C module using the following procedure:

To prevent a function name from being mangled, the function definition and all declarations used by the C++ code must use extern "C".

You cannot call member functions of classes in C++ from C. When a member function routine is needed, call a non-member function in C++. This in turn calls the member function.

Since the C program cannot directly create or destroy C++ objects, it is the responsibility of the writer of the C++ class library to define interface routines that call constructors and destructors, and it is the responsibility of the C user to call these interface routines to create such objects before using them and to destroy them afterwards.

The C user should not try to define an equivalent struct definition for the class definition in C++. The class definition may contain bookkeeping information that is not guaranteed to work on every architecture. All access to members must be done in the C++ module.

The following examples illustrate some of these points, as well as reference parameters in the interface routine to the constructor.

//**************************************************

// C++ module that manipulates object obj. * //************************************************** #include <iostream.h>

typedef class obj* obj_ptr;

extern “C” void initialize_obj (obj_ptr& p); extern “C” void delete_obj (obj_ptr p); extern “C” void print_obj (obj_ptr p);

struct obj { private:

int x;

public:

obj() {x = 7;}

friend void print_obj(obj_ptr p);

};

Data Compatibility between C and C++ 191

Page 191
Image 191
HP C/aC++ for PA-RISC Software manual HP C Calling HP aC++, Running the Example, Enter the nameJoann Joann has a balance