码迷,mamicode.com
首页 > 其他好文 > 详细

TThreadMethod and TThreadProcedure

时间:2014-10-02 19:50:43      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   ar   for   sp   c   

http://embarcadero.newsgroups.archived.at/public.delphi.rtl/201112/1112035763.html

> Hi,
>
> What is the difference between these two definitions:
>
>  TThreadMethod = procedure of object;
>  TThreadProcedure = reference to procedure;
>
> Please can you try to explain simply :)

Well, it is not exactly a simple subject ;-)

TThreadMethod declares a method pointer type.

Internally, a method pointer is represented as a record of two pointers (there is a type TMethod for that).

TMethod = record
    code: pointer;
    data: pointer
  end;

If you declare a variable of a method pointer type you can only assign
it a method of an object. Wayne‘s example is wrong here since it uses
the @ operator. You do not use that for assigning a method to a method
pointer variable.

    TMyClass = class
    private
        MyMethod: ThreadMethod;
        procedure Foo;

  MyMethod := Foo;

On this assignment the compiler internally executes

  TMethod(MyMethod).Code := @TMyClass.Foo;
  TMethod(MyMethod).Data := self;  // actually the address of the object Foo belongs to

Calling the method through the method pointer will pass the Data value
as the hidden Self parameter to Foo. So you can only use a method
pointer safely as long as the object the pointer refers to still exists.

TThreadProcedure = reference to procedure;

This declares a new-fangled thing called an anonymous method, but it is
in fact more generally useful than the use  Wayne showed. To a variable
of type TThreadProcedure you could assign not only a nameless procedure
constructed on the fly, but also an existing method of some object, or
even a standalone procedure. The compiler does a lot more work behind
the scene for these types. It creates a whole class with a matching
interface type, creates an instance, stores any local variables the
anonymous method refers to into this instance, implements the anonymous
method as a method of this class, calls it, cleans up afterwards.
"reference to x" types are not simple types, unlike method or function
pointer types. They have considerable overhead in terms of code size
and execution, but are a lot more flexible in turn.

Anonymous methods are Delphi‘s implementation of a computer science
concept called a closure (see
http://en.wikipedia.org/wiki/Closure_%28computer_science%29 )

-- 

TThreadMethod and TThreadProcedure

标签:style   http   color   io   os   ar   for   sp   c   

原文地址:http://www.cnblogs.com/shangdawei/p/4004323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!