Get the address of an Objective-c property (which is a C struct)

前端 未结 4 453
南笙
南笙 2020-12-19 08:56

I have an Objective-C class which contains a C-style struct. I need to call a C function passing a pointer to this object member (a.k.a. property). For the life of me, I c

4条回答
  •  太阳男子
    2020-12-19 09:35

    There are often pretty good reasons to do what the original post is asking, given that Objective-C apps often have to work with C/C++ API's that take pointers to structs and similar types, but in a Cocoa app you'll often want to store such data in Objective-C classes for data management, collection in arrays and dictionaries, etc.

    Though this question has been up for awhile I don't see the clear answer, which is: you can have a method that returns the address of the data that's backing your property, but in that method don't use "self" or it will go through the accessor and still not work.

    - (const MyStruct*) getMyStructPtr
    {
        return &mystruct;
    }
    

    Note that I'm using the declared property from the OP, but not referencing it as self.mystruct, which would generate a compiler error (because that invokes the synthesized getter method).

提交回复
热议问题