问题描述
我有一个Objective-C类,其中包含C样式的结构.我需要调用一个C函数,将一个指针传递给该对象成员(也就是属性).为了我的一生,我不知道该如何获取此C结构的地址.使用传统的&
运算符获取地址,我遇到了LValue编译器错误.
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 can't figure out how to get the address of this C struct. Using the traditional &
operator to get the address, I'm getting an LValue compiler error.
typedef struct _myStruct
{
int aNumber;
}MyStruct, *pMyStruct;
@interface MyClass : NSObject {
MyStruct mystruct;
}
@property (readwrite) MyStruct myStruct;
@end
以下代码导致编译器错误:
The following code results in a compiler error:
MyClass* myClass = [[MyClass alloc] init];
MyStruct* p = &(myClass.myStruct);
如何获取指向myClass
对象的myStruct
成员的指针?
How do I get a pointer to the myStruct
member of the myClass
object?
推荐答案
考虑到Objective-C应用程序通常必须使用带有指针的C/C ++ API,通常会有很多很好的理由来完成原始帖子所要求的到结构和类似类型,但是在Cocoa应用程序中,您通常需要将此类数据存储在Objective-C类中以进行数据管理,数组和字典中的收集等.
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.
尽管这个问题已经存在了一段时间,但我仍然没有一个明确的答案,那就是:您可以使用一个方法来返回支持属性的数据的地址,但是在该方法中请不要使用"self ",否则它将通过访问器仍然无法正常工作.
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;
}
请注意,我使用的是OP中声明的属性,但未将其引用为self.mystruct
,这会产生编译器错误(因为调用了合成的getter方法).
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).
这篇关于获取一个Objective-c属性的地址(这是一个C结构)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!