سؤال

I have the following in my WinRT component:

public value struct WinRTStruct
{
    int x;
    int y;
};

public ref class WinRTComponent sealed
{
    public:
    WinRTComponent();
    int TestPointerParam(WinRTStruct * wintRTStruct);
};

int WinRTComponent::TestPointerParam(WinRTStruct * wintRTStruct)
{
    wintRTStruct->y = wintRTStruct->y + 100;
    return wintRTStruct->x;
}

But, it seems that the value of winRTStruct->y and x are always 0 inside the method, when called from C#:

WinRTComponent comp = new WinRTComponent();
WinRTStruct winRTStruct;
winRTStruct.x = 100;
winRTStruct.y = 200;
comp.TestPointerParam(out winRTStruct);
textBlock8.Text = winRTStruct.y.ToString();

What is the correct way to pass a struct by reference so it an be updated inside the method of a WinRTComponent written in C++/CX?

هل كانت مفيدة؟

المحلول

You cannot pass a struct by reference. All value types (including structs) in winrt are passed by value. Winrt structs are expected to be relatively small - they're intended to be used for holding things like Point and Rect.

In your case, you've indicated that the struct is an "out" parameter - an "out" parameter is write-only, its contents are ignored on input and are copied out on return. If you want a structure to be in and out, split it into two parameters - one "in" parameter and another "out" parameter (in/out parameters are not allowed in WinRT because they don't project to JS the way you expect them to project).

نصائح أخرى

My co-worker helped me solve this. In WinRT components, it seems that the best way to do this is to define a ref struct instead of a value struct:

public ref struct WinRTStruct2 sealed
{
private: int _x;
public:
 property int X
 {
    int get(){ return _x; }
    void set(int value){ _x = value; }
 }
private: int _y;
public:
 property int Y
 {
    int get(){ return _y; }
    void set(int value){ _y = value; }
 }
};

But this creates other problems. Now the VS11 compiler gives INTERNAL COMPILER ERROR when I try to add a method to the ref struct that returns an instance of the struct.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top