从头开始重新实现 NSObject
当我阅读新的 4.0.2 iOS 更新时,我想知道黑客会做什么或尝试如何处理缓冲区溢出,在查阅了一些维基百科后,我对使用 malloc 产生了兴趣,从而创建了自己的“NSObject”。
我实际上并不打算在我的任何应用程序中使用它,它只是为了学习和使用 Objective-C。
当然,不出所料,我遇到了一些我自己无法解决的问题。
为了创建我的对象,我这样做:
+ (id)create{ return malloc(sizeof(self)); }
以及
- (void)free { free(self); }
当调用 [TestObject create] 时;我收到以下控制台消息:
“8/11/10 11:17:31 PM TestingHeap[2675] *** NSInspiration: warning: object 0x100002100 of class 'AObject' does not Implement doesNotRecognizeSelector: -- abort”
所以它试图将我的对象作为 NSObject 处理..?以及我该如何解决这个问题。
另外,在没有 Foundation 或 AppKit 的情况下进行编译时,我会收到缺少符号的错误, 特别是 __objc_empty_vtable 和 __objc_empty_cache。 我已经尝试包含 /usr/include/objc/ 中的几个头文件
提前致谢。
更新
与 libobjc 链接后,当尝试从我的类中调用方法时,我收到 EXC_BAD_INSTRUCTION。
When I was reading about the new 4.0.2 iOS update I wanted to know what hackers do or try doing with a buffer overflow, which after some wikipedia'ing got me interested in playing with malloc and thus creating my own "NSObject".
I am not actually planning to use this in any of my applications, its only for learning and playing around with objective-c.
And of course, as expected I encountered some problems which I couldn't solve myself.
for creating my object I do:
+ (id)create{ return malloc(sizeof(self)); }
and
- (void)free { free(self); }
When calling [TestObject create]; I get the following console messages:
"8/11/10 11:17:31 PM TestingHeap[2675] *** NSInvocation: warning: object 0x100002100 of class 'AObject' does not implement doesNotRecognizeSelector: -- abort"
So its trying to handle my object as an NSObject.. ? and how do I solve this.
Also when compiling without Foundation or AppKit, I get an error for missing symbols,
__objc_empty_vtable and __objc_empty_cache in particular.
I've tried including several header files from /usr/include/objc/
Thanks in advance.
Update
After linking with libobjc I receive EXC_BAD_INSTRUCTION when trying to call a method from my class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 David 指出的那样,您需要使用
class_getInstanceSize
而不是sizeof
。您需要链接到 libobjc (正如您自己发现的那样)。
您的基类需要一个
isa
指针,该指针必须在您的create
方法中设置。并且运行时需要实现一个 +initialize 方法,该方法将在第一次使用您的类之前调用。如果缺少它就会崩溃。
因此,您的基类中的所有内容至少应该具有以下内容:
You need to use
class_getInstanceSize
instead ofsizeof
, as David pointed out.You need to link against libobjc (as you found out yourself).
Your base class requires a
isa
pointer which has to be set in yourcreate
method.And the runtime requires a
+initialize
method to be implemented which will be called before your class is used the first time. If it is missing it crashes.So all things together your base class should have at least this: