oz10
oz10

Reputation: 158344

Can you call Ada functions from C++?

I'm a complete Ada newbie, though I've used Pascal for 2-3 years during HS.

IIRC, it is possible to call Pascal compiled functions from C/C++. Is it possible to call procedures & functions written in Ada from C++?

Upvotes: 8

Views: 5471

Answers (4)

Glen
Glen

Reputation: 83

Here's an example using g++/gnatmake 5.3.0:

NOTE: Be careful when passing data between C++ and Ada

ada_pkg.ads

    package Ada_Pkg is
        procedure DoSomething (Number : in Integer);
        pragma Export (C, DoSomething, "doSomething");
    end Ada_Pkg;

ada_pkg.adb

    with Ada.Text_Io;
    package body Ada_Pkg is
        procedure DoSomething (Number : in Integer) is
        begin
            Ada.Text_Io.Put_Line ("Ada: RECEIVED " & Integer'Image(Number));
        end DoSomething;
    begin
        null;
    end Ada_Pkg;

main.cpp

    /*
    TO BUILD:
    gnatmake -c ada_pkg
    g++ -c main.cpp
    gnatbind -n ada_pkg
    gnatlink ada_pkg -o main --LINK=g++ -lstdc++ main.o
    */

    #include <iostream>

    extern "C" {
        void doSomething (int data);
        void adainit ();
        void adafinal ();
    }

    int main () {
        adainit(); // Required for Ada
        doSomething(44);
        adafinal(); // Required for Ada 
        std::cout << "in C++" << std::endl;
        return 0;
    }

References:

Upvotes: 7

DarenW
DarenW

Reputation: 16906

Yes. Several years ago I wrote a short simple demo to prove it. There were two DLLs, one written in C++ and the other in Ada. They just added constants to floating point values. Two apps, one in C++ and one in Ada, each used both the DLL. So every possible combination of C++ calling/called from Ada existed. It all worked fine. This was on Windows whatever version was current at the time; I don't recall but may have gotten this working on Linux or BeOS.

Now if only I could find the source code from that...

Upvotes: -1

VonC
VonC

Reputation: 1324606

According to this old tutorial, it should be possible.

However, as illustrated by this thread, you must be careful with the c++ extern "C" definitions of your Ada functions.

Upvotes: 7

T.E.D.
T.E.D.

Reputation: 44804

That kind of thing is done all the time. The trick is to tell both sides to use a "C"-style calling protocol for the routine. In C++ this is done with extern "C" declarations, and in the Ada side with pragma Export ("C", ...

Look those up in your favorite respective reference sources for details. Watch out for pointer and reference paramters!

Upvotes: 1

Related Questions