C/C++ struct interfacing

Oleg B code.viator at gmail.com
Sun Oct 27 05:20:48 PDT 2013


Hello.
I want use one struct in two language.
How to declare the same structure in different languages​​?

D code: calling C++ function with my struct
<code>
extern(C++)
{
     struct vec(size_t N, T=float)
     { // << line 6
         alias vec!(N,T) thistype;
         T[N] data;

         auto opBinary(string op)( in thistype rhs ) const
         {
             thistype ret;
             foreach( i; 0 .. N ) ret.data[i] = data[i] + 
rhs.data[i];
             return ret;
         }
     }

     void cppcall( vec!(3,float) d );
}

void main()
{
     vec!3 a, b;
     a.data[0] = 10;
     a.data[1] = 7;
     a.data[2] = 3;

     b.data[0] = 13;
     b.data[1] = 9;
     b.data[2] = 4;

     cppcall( a + b );
}
</code>

C++ code: use struct data
<code>
#include <cstdio>

struct vec
{
     float data[3];
};

void cppcall( vec d )
{
     printf( "%f %f %f\n", d.data[0], d.data[1], d.data[2] );
}
</code>

compilation failed with unclear error

$ g++ -c ctypestest.cpp -o ctypestest.o
$ dmd ctypestest.d ctypestest.o -ofctypestest
ctypestest.d(6): Error: struct ctypestest.vec!(3, float).vec C++ 
static variables not supported


More information about the Digitalmars-d-learn mailing list