Skip to content

Instantly share code, notes, and snippets.

@ytomino
Last active July 25, 2019 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytomino/3e9a146f0a8938d6e44c710ec5ffea08 to your computer and use it in GitHub Desktop.
Save ytomino/3e9a146f0a8938d6e44c710ec5ffea08 to your computer and use it in GitHub Desktop.
Ada tagged record derived from C++ class
package body adaside is
use type Interfaces.C.int;
function Constructor (n : Interfaces.C.int) return T is
begin
return (cppclass_hpp.Class_cppclass_t.New_cppclass_t (n)
with null record);
end Constructor;
overriding function get (this : access T) return Interfaces.C.int is
begin
return this.n_u * 2; -- replace the body
end get;
end adaside;
with Interfaces.C;
with cppclass_hpp;
package adaside is
type T is new cppclass_hpp.Class_cppclass_t.cppclass_t with null record;
function Constructor (n : Interfaces.C.int) return T;
overriding function get (this : access T) return Interfaces.C.int;
end adaside;
#include "cppclass.hpp"
cppclass_t::cppclass_t(int n): n_(n) { }
// g++ -c cppclass.cpp
class cppclass_t {
cppclass_t(int n);
int n_;
virtual int get() { return n_; }
};
// gcc -fdump-ada-spec cppclass.hpp
pragma Ada_2005;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
package cppclass_hpp is
package Class_cppclass_t is
type cppclass_t is tagged limited record
n_u : aliased int; -- cppclass.hpp:3
end record;
pragma Import (CPP, cppclass_t);
function New_cppclass_t (n : int) return cppclass_t; -- cppclass.hpp:2
pragma CPP_Constructor (New_cppclass_t, "_ZN10cppclass_tC1Ei");
function get (this : access cppclass_t) return int; -- cppclass.hpp:4
pragma Import (CPP, get, "_ZN10cppclass_t3getEv");
end;
use Class_cppclass_t;
end cppclass_hpp;
with Ada.Text_IO;
with Interfaces.C;
with cppclass_hpp;
with adaside;
procedure main is
Obj : access cppclass_hpp.Class_cppclass_t.cppclass_t'Class := -- pointer to the base type
new adaside.T'(adaside.Constructor (10)); -- allocating the derived type
use Ada.Text_IO;
package int_IO is new Integer_IO (Interfaces.C.int);
use int_IO;
begin
Put (Obj.get); -- calling the virtual function
New_Line;
end main;
-- gnatmake main.adb -largs cppclass.o -lstdc++
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment