www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - C++ interfaces and D dynamic arrays

reply Void-995 <void995 gmail.com> writes:
Hi, everyone.

I would like to have an interface that can be implemented and/or 
used from C++ in D. One of the things I would like to keep is the 
nice feature of D dynamic arrays in terms of bounding checks and 
"length" property.

Let's assume:

extern (C++) interface ICppInterfaceInD {
   ref const(int[]) indices() const;
}

class A: ICppInterfaceInD {
   private int[] m_indices;

   extern (C++) ref const(int[]) indices() const {
     return m_indices;
   }
}

All I want is keeping const correctness like in C++ so no one can 
modify m_indices and use that as property within const pointer. I 
thought it may be passed to C++ as some struct of sort:

struct wrappedArrray(T) {
   size_t length;
   T* ptr;
}

but it just don't want to be friendly with me.

How should I rethink the interface with being D-way efficient 
when using that interface inside of D?
Jan 02 2018
parent Jacob Carlborg <doob me.com> writes:
On 2018-01-02 17:48, Void-995 wrote:
 Hi, everyone.
 
 I would like to have an interface that can be implemented and/or used 
 from C++ in D. One of the things I would like to keep is the nice 
 feature of D dynamic arrays in terms of bounding checks and "length" 
 property.
 
 Let's assume:
 
 extern (C++) interface ICppInterfaceInD {
    ref const(int[]) indices() const;
 }
 
 class A: ICppInterfaceInD {
    private int[] m_indices;
 
    extern (C++) ref const(int[]) indices() const {
      return m_indices;
    }
 }
 
 All I want is keeping const correctness like in C++ so no one can modify 
 m_indices and use that as property within const pointer. I thought it 
 may be passed to C++ as some struct of sort:
 
 struct wrappedArrray(T) {
    size_t length;
    T* ptr;
 }
 
 but it just don't want to be friendly with me.
 
 How should I rethink the interface with being D-way efficient when using 
 that interface inside of D?
I would recommend using a struct as above or pass the pointer and length separately. Then create a function on the D side that coverts between the struct and a D array. Note that you cannot use a D array in a C++ interface, it will fail to compile. -- /Jacob Carlborg
Jan 02 2018