简体   繁体   English

在Objective-C中初始化为类变量时,在哪种内存上分配C结构

[英]On which kind of memory a C struct is allocated when initialized as a class variable in Objective-C

Consider the following: 考虑以下:

typedef struct
{
  float m00, m01, m02, m03;
  float m10, m11, m12, m13;
  float m20, m21, m22, m23;
  float m30, m31, m32, m33;
} Matrix;

@interface TestClass : NSObject
{
  Matrix matrix;
}

- (TestClass *) init;
@end

@implementation TestClass
- (TestClass *) init
{
  self = [super init];
  matrix = (Matrix) {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
  return self;
}
@end

How to ensure that the 64 bytes allocated with the struct are properly released whenever the "matrix" variable is not relevant anymore (or whenever the whole object is released)? 如果“矩阵”变量不再相关(或者整个对象被释放时),如何确保正确释放分配给struct的64个字节?

In this case matrix should be embedded in the struct that is generated by the ObjectiveC compiler for instances of TestClass. 在这种情况下,矩阵应该嵌入在ObjectiveC编译器为TestClass实例生成的结构中。 Its lifetime is bound to the instance of TestClass which it is part of, just like an int or float member would be. 它的生命周期绑定到它所属的TestClass实例,就像int或float成员一样。

You can easily test this, if you inspect the pointers. 如果检查指针,可以轻松测试。

TestClass* testAddress = [[TestClass alloc] init];
Matrix* matrixAddress = &(testAddress->matrix);

int rawTest = (int) testAddress;
int rawMatrix = (int) matrixAddress;
int memberOffset = rawMatrix - rawTest;

printf("%i", memberOffset);

I have no compiler here, but I guess it will just mumble some warnings about evil typecasts and generate the code anyways. 我这里没有编译器,但我想它只会嘟嘟一些关于邪恶的类型转换的警告并反正生成代码。 The output should be constant, something like 4 or 8, depending on your target architecture. 输出应该是常量,例如4或8,具体取决于您的目标体系结构。

In this case, there's absolutely nothing that you have to do to the structure to get free its memory when the object containing it is deallocated. 在这种情况下,当对包含它的对象进行解除分配时,您必须对结构进行任何操作以释放其内存。 The memory for the structure is inline in the object. 结构的内存在对象中是内联的。

As an aside, the Core Animation struct CATransform3D has the same internal structure as your matrix: 另外,Core Animation结构CATransform3D具有与矩阵相同的内部结构:

struct CATransform3D
   {
   CGFloat m11, m12, m13, m14;
   CGFloat m21, m22, m23, m24;
   CGFloat m31, m32, m33, m34;
   CGFloat m41, m42, m43, m44;
};

Instead of defining a custom type, you may wish to use this one that Apple provides. 您可能希望使用Apple提供的这种类型,而不是定义自定义类型。 Apple also provides some very handy functions for manipulating these matrices. Apple还为操作这些矩阵提供了一些非常方便的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM