1

I have objective-c class in iOS, there is a field whose type is c++ class. I don't have the definition of the c++ class.
How to get the value of this field ?
And how to change the field value of this c++ typed field ?
For example.

@interface A 
    B b // c++ type
@end

class B {
    int c;
}

How to get the value of b ? How to change the value of c?

nameless
  • 2,015
  • 2
  • 11
  • 10

2 Answers2

0

With accessor and mutator a.k.a. getter/setters:

class B {
  public:
    int getC() { return c };
    void setC(int c_) { c = c_ };
  private:
    int c;
}

int main()
{
    B b;

    B.setC(50); // c = 50

    int x = B.getC() // x = 50;

    return 0;
}
not an alien
  • 651
  • 4
  • 13
0

Edit: I misread your question.

Disclaimer: I don't have access to an iOS toolchain at the time of this writing to verify the Objective-C info, but I'm confident in this answer based on my past experience working with Objective-C & iOS.

The Objective-C runtime provides type introspection.

If the C++ member is a field:
Use the technique in this post or similar, then isolate the ivar you're interested in.
If using the loop technique from the aforementioned post:

if (strcmp(name, "target_field") == 0) {
    ptrdiff_t offset = ivar_getOffset(var);
    CppObject* cppObject = (CppObject*)(((ptrdiff_t*)&targetObjcInst) + offset);
    // Access the public members of CppObject...
}

If the C++ member is a property:
Were you simply accessing an Obj-C property value, I'd say follow this answer and call it a day, but because it's a C++ property value, the details are unclear. I'm not sure it's even possible.

C++ has the concept of friendship providing access to the non-public members of one type from another.

i.e.

class A;

class B {
    friend class A;

    int C;
};

class A {
    int D;

    int sum(const B& b) {
        return b.C + D;
    }
};

This doesn't extend to Objective-C. Barring some specific compiler extension I'm unaware of, Obj-C interfaces can't be "friends" with C++ types, thus Obj-C can't access the private components of C++ types. Providing a public accessor/mutator or making the field public are your only portable options.

Koby Duck
  • 1,118
  • 7
  • 15