Struct constructor, opCall mess.

Maxim Fomin maxim at maxim-fomin.ru
Mon Feb 24 23:37:43 PST 2014


On Monday, 24 February 2014 at 19:41:57 UTC, Remo wrote:
> For Vector example this works pretty well this way.
> But my main problem is more complicated.
>
> extern(C)  int init(ref CWrapper p);
> extern(C) void free(ref CWrapper p);
>
> struct CWrapper
> {
>   //some data that must be the same at C side.
>   Data m_data;
>
>   this() {
>      init(&this);
>   }
>   ~this() {
>      free(&this);
>   }
> }
>
> How to do something like this in D ?
> Using class appears for me to be wrong direction.
>

1) Please comment after previous speaker, not before.

You can't avoid default struct constructor problem if functions 
which you call in constructors are not at least CTFEable because 
you would need to call them if you wish to define default struct 
constructor. Since this is not your case, you can do:

2) You can use static OpCall, Voldemort type or alias this. In 
case of alias this it looks like:

extern(C) int printf(const char*, ...);

extern(C)  int init(CWrapper* p) { printf("init\n"); return 0; }
extern(C) void d_free(CWrapper* p) { printf("free\n"); }

struct Data { void do_something(){} }

struct CWrapper
{
   //some data that must be the same at C side.
   Data m_data;
   bool m_init;

   /*this(int) {
      init(&this);
   }*/
   ~this() {
      d_free(&this);
   }
   Data get()
   {
	  if (!m_init)
		  init(&this);
	  return m_data;
   }
	alias get this;
}


void main()
{
	CWrapper cw;
	cw.do_something();
	
}

In case of Voldermort struct some struct is defined inside 
function, so the only way (in theory) to create an instance is to 
call that function. It is inconviniet but guarantees that you 
will not have non initialzed structs (in theory).

extern(C) int printf(const char*,...);


auto make_struct()
{
	struct Data{}
	struct CWrapper
     {
	  extern(C)  int m_init(CWrapper* p){ return 0; }
       extern(C) void m_free(CWrapper* p){ printf("free\n");}
       //some data that must be the same at C side.
       Data m_data;

      this(int) {
        m_init(&this);
      }
      ~this() {
        m_free(&this);
      }
     }

	return CWrapper(0);
}

void main()
{
	auto x = make_struct();
}

4) Please do not define free() function.


More information about the Digitalmars-d-learn mailing list