Vision

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 23 13:38:27 PDT 2015


On 2015-10-23 17:53, Kagamin wrote:

> A little of massage and you get:
>
> struct ClassStorage(C)
> {
>    alias lookUp this;
>    C lookUp() immutable
>    {
>      return cast(C)objc_lookUpClass(C.stringof);
>    }
> }
>
> immutable ClassStorage!NSString cNSString;
>
> C alloc(C)()
> {
>    immutable ClassStorage!C c;
>    return c.alloc();
> }
>
> void main()
> {
>    auto str = cNSString.alloc.initWithUTF8String("Hello World!");
>    auto str1 = alloc!NSString.initWithUTF8String("Hello World!");
>    NSLog(str);
>    str.release();
>    str1.release();
> }

In theory this could work:

extern (C) void NSLog(NSString, ...);
extern (C) Class objc_lookUpClass(in char*);

extern (Objective-C)
interface Class
{
     // prefix with an underscore to avoid conflict with the class
     // method in NSObject
     NSObject _alloc() @selector("alloc");
}

extern (Objective-C)
interface NSObject : Class
{
     // prefix with an underscore to avoid conflict with the
     // free function
     NSObject _init() @selector("init");

     static T alloc(this T)()
     {
         // The cast to void* is necessary to bypass the runtime
         // because casting is not yet implemented for Objective-C
         // classes
         return cast(T) cast(void*) objc_lookUpClass(T.stringof)._alloc;
     }
}

// Use a free function and UFCS because the @selector attribute is not
// allowed on template methods
auto init (T : NSObject)(T obj)
{
     return cast(T) obj._init();
}

extern (Objective-C)
interface NSString : NSObject
{
     NSString initWithUTF8String(in char* str) 
@selector("initWithUTF8String:");
}

void main()
{
     auto str = NSString.alloc.initWithUTF8String("Hello World!!");
     auto str2 = NSString.alloc.init;
     NSLog(str);
}

The above could work, and in my opinion should work. But the "this T" 
for static methods don't work.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list