event declaration and FieldOffsetAttribute using

2

i have a CLR class which uses the Attribute StructLayout attribte:

[StructLayout(LayoutKind::Explicit)]
public ref class Matrix4 : System::ComponentModel::INotifyPropertyChanged

All fields make use of the FieldOffset attribute. Now i need to add an event, in particular i want to implment the INotifyPropertyChanged interface and hence i need the

[FieldOffset(16*sizeof(Real))]
virtual event System::ComponentModel::PropertyChangedEventHandler^ PropertyChanged;

event. The compiler tells me I need to assign the FieldOffset attribute to this event, but after doing that the compiler throws the error message:

Error   34  error C1093: API call 'DefineCustomAttribute' failed '0x801311c0'

I am not allowed to chage StructLayout to Sequential so how do i solve this issue?

Any help would be appreciated,

Best, apo.

SOLVED by separating:

protected:
    [field:FieldOffset(16*sizeof(Real))]
    System::ComponentModel::PropertyChangedEventHandler^ _pc;
public:

    virtual event System::ComponentModel::PropertyChangedEventHandler^ PropertyChanged
    {
        void add(System::ComponentModel::PropertyChangedEventHandler^ p) 
        {
            _pc += p;
        }
        void remove(System::ComponentModel::PropertyChangedEventHandler^ p) 
        {
            _pc -= p;
        }
        void raise(Object ^sender, System::ComponentModel::PropertyChangedEventArgs ^ args) 
        {
            _pc->Invoke(sender, args);
        }       
    };
    void OnPropertyChanged(String^ info)
    {
        PropertyChanged(this, gcnew System::ComponentModel::PropertyChangedEventArgs(info));
    }
.net
c++-cli
clr
asked on Stack Overflow Jun 28, 2011 by user819068 • edited Jun 28, 2011 by user819068

1 Answer

1

Does the attribute you've added apply to the event? or to the field? I'm not a C++ guru, but that looks like a C++ implementation of a "field-like event". The [FieldOffset] attribute only applies to the backing field - not the event. In C#, you would target the field via:

[field:FieldOffset(yourOffset)]
public event PropertyChangedEventHandler PropertyChanged;

so: make sure you are targetting the field. I can't advise on the C++ syntax for that, though. Maybe there isn't one and you need to use an explicit event implementation with a field you add yourself (and can then decorate).

This is supported by a quick search that shows that error number linked to:

failed '0x801311c0'

Description: The custom attribute is not valid for the target object's type.

which is exactly what I would expect to see if targeting the event rather than the field.

As an aside - events on structs are tricky beasts...

answered on Stack Overflow Jun 28, 2011 by Marc Gravell

User contributions licensed under CC BY-SA 3.0