pinning revisited

Dave Dave_member at pathlink.com
Thu Jul 20 22:00:53 PDT 2006


Jason O'Brien wrote:
> It's not that any of us need to pin right now, but that the standard
> puts anyone using C interop in a hard place: It's not possible to write
> forward-compatible gc safe code.  We want to, but we can't, and so we
> don't.  Noone is right now, and I'm afraid the more broken code we all
> write the less likely it is a more efficient copying collector will ever
> be worthwhile, and if it does get done all the more code we have to 
> rewrite.
> 
> I have a couple of ideas, but whatever we decide on we should do it soon.
> 

The concern is valid and your ideas are good ones IMO. But for now we 
can always get around using the GC by using malloc/free, etc.

Another idea: Why not just make it easier to de/alloc using the crt and 
place those into "auto blocks" (for now).

import std.stdarg, std.c.stdlib : malloc, free;
extern(C)
{
     char* strncpy(char*,char*,size_t);
     size_t strlen(char*);
}

void main()
{
     size_t len = 100;
     with(new SafeCStr(len,len))
     {
         const char[] str = "abcdefg...";
         char* s = ptrs[0], d = ptrs[1];
         strncpy(s,str,str.length);
         strncpy(d,s,str.length);
         printf("%s: %d\n",d,strlen(d));
     }
}

auto class CAlloc(T)
{
     T*[] ptrs;
     this(...)
     {
         for(size_t idx = 0; idx < _arguments.length; idx++)
         {
             if(_arguments[idx] != typeid(int) &&
                _arguments[idx] != typeid(size_t))
                 throw new Exception("wrong type of arg");

             long len = va_arg!(int)(_argptr);

             if(len < 0)
                 throw new Exception("invalid allocation length");

             ptrs ~= cast(T*)malloc(len * T.sizeof);

             if(ptrs[idx] is null)
                 throw new Exception("allocation failed");
         }
     }
     ~this()
     {
         foreach(inout ptr; ptrs)
         {
             if(ptr)
             {
                 free(ptr);
                 ptr = null;
             }
         }
     }
}
alias CAlloc!(char) SafeCStr;



More information about the Digitalmars-d mailing list