Accessing Private Fields from Outside
Robert Jacques
sandford at jhu.edu
Tue May 17 17:55:25 PDT 2011
On Tue, 17 May 2011 20:52:02 -0400, Robert Jacques <sandford at jhu.edu>
wrote:
> On Tue, 17 May 2011 20:44:24 -0400, Mehrdad <wfunction at hotmail.com>
> wrote:
>
>> On 5/17/2011 5:13 PM, Robert Jacques wrote:
>>> On Tue, 17 May 2011 19:47:29 -0400, Mehrdad <wfunction at hotmail.com>
>>> wrote:
>>>
>>>> Is there any (hacky) way of accessing a private field from outside a
>>>> data type? (The equivalent of reflection in managed languages.)
>>>>
>>>> I'm trying to write a piece of marshaling code that needs access to a
>>>> data type's fields, but can't access them because it's not allowed
>>>> to. :(
>>>
>>> The short answer:
>>> T.tupleof works for anything that you have the source to, but doesn't
>>> support polymorphism out of the box.
>>>
>>> The long answer (from my json library):
>>> static Value from(T)(T value) {
>>> static if(is(T == class) ) if( value is null ) return
>>> Value(Null.init);
>>> //...
>>> static if(is(T == struct) || is(T == class)) {
>>> Value[string] result;
>>> foreach(i,v;value.tupleof) {
>>> result[value.tupleof[i].stringof["value.".length..$]]
>>> = from(v);
>>> }
>>> return Value( result );
>>> }
>>> //..
>>> }
>>>
>>> P.S. Are you marshaling to/from an open format or something
>>> proprietary?
>> T.tupleof has a problem though: It doesn't seem to let me actually
>> access the value; it just give me a tuple I can't do anything with.
>> Your example only gets the name of the field, but you never actually
>> seem to access it.
>>
>> (P.S.: I'm trying to marshal from/to Windows data structures, so I
>> guess it's kinda both?)
>
> I actually do both (name and value) in the above example.
> Name: value.tupleof[i].stringof["value.".length..$]
> Value: v
> You can also use value.tupleof[i] if all you want is to set a field.
P.S. In fact, since foreach(i,ref v;value.tupleof) won't compile, you have
to use value.tupleof[i] to assign to a field.
More information about the Digitalmars-d
mailing list