« [番外]咳さんに褒められていた件 | メイン | 4章.参照渡しと値渡し (その6) »

4章.参照渡しと値渡し (その5)

dRubyでの参照渡しの続きです。dRubyでの参照渡しは、厳密に言うと参照オブジェクトの値渡しであることは前回学びました。参照オブジェクトとはDRbObjectのことなので、まずDRbObjectの内容を見ていくようにしましょう。
DRbObjectには二つのインスタンス変数があります。


@ref

オブジェクトの実体のID(hoge.__id__したものです。)

@url

dRubyサーバーを特定するURI


DRbObjectをnewするときに何かオブジェクトを渡すと、それが@refに入ります。例えばirbでこんなことをやってみます。

[サーバー側]

irb(main):001:0> require 'drb/drb'
=> true
irb(main):002:0> uri = 'druby://サーバーのホスト名:9898'
=> "druby://サーバーのホスト名:9898"
irb(main):003:0> h = {}
=> {}
irb(main):004:0> DRb.start_service(uri, h)
=> #<DRb::DRbServer:0x295ecd0 ・・・
irb(main):005:0> str = 'foo'
=> "foo"
irb(main):006:0> str.__id__
=> 21680810
irb(main):007:0> ref = DRbObject.new(str)
=> #<DRb::DRbObject:0x29530b0 @ref=21680810, @uri="druby://サーバーのホスト名:9898">
irb(main):008:0> h[1] = ref
=> #<DRb::DRbObject:0x29530b0 @ref=21680810, @uri="druby://サーバーのホスト名:9898">

 最後から2つ目の行(:007)を見ます。ここで作成したDRbObjectのインスタンスの内容を確認します。@refは、引数に渡されたstrというオブジェクトのIDが設定されています。@uriは、start_service時に指定したuriが入っています。DRbObjectのインスタンスを作ると、dRubyサービスのURIとオブジェクトが自動的に紐付きます。

 なお、前回のエントリで確認したように、DRbObjectのインスタンスを作る前にstart_serviceしてないとdRubyサービスが無いのでエラーになります。ただ、すっかりおなじみのnew_with_uriだけは特殊で、指定したURIのフロントオブジェクトに対する参照をもらうだけなのでstart_serviceしてなくても大丈夫です。irbをもうひとつ立ち上げて、クライアント側から(new_with_uriを使って)サーバーのフロントオブジェクトを取得するスクリプトを見ます。このエントリではこの2つのirbをそのまま使い続け、どんどん追記していきます。どちらのことか判断しやすいように、各々[サーバー側]と[クライアント側]という風に明記することにします。

[クライアント側]

irb(main):001:0> require 'drb/drb'
=> true
irb(main):002:0> there = DRbObject.new_with_uri('druby://サーバーのホスト名:9898')
=> #<DRb::DRbObject:0x29a5f68 @ref=nil, @uri="druby://サーバーのホスト名:9898">

この場合、@refはnilです。本にも

@refがnilの場合は特別にURIに関連づけられたフロントオブジェクトを参照します。

4.1.2 dRubyでは?

と記載がありますね。ちなみに前にも見たかもしれないですが、DRbObjectのnew_with_uri(uri)は、DRbObject.new(nil, uri)と同じです。

# Create a new DRbObject from a URI alone.
def self.new_with_uri(uri)
 self.new(nil, uri)
end

では、クライアントのirbから操作を続けてみます。

[クライアント側]

irb(main):003:0> s = there[1]
=> #<DRb::DRbObject:0x29a59a0 @ref=21680810, @uri="druby://サーバーのホスト名:9898">

これは、先ほどサーバーで作成したDRbObjectです。@refは21680810ですね。サーバー側のオブジェクトIDが設定されています。参照オブジェクトに対する操作をクライアント側で引き続き行ってみます。

[クライアント側]

irb(main):004:0> s.upcase!

これをしてから、サーバー側のirbを操作して中身を確認してみましょう。

[サーバー側]

irb(main):009:0> str
=> "FOO"
irb(main):010:0> ref.to_s
=> "FOO"
irb(main):011:0> h[1].to_s
=> "FOO"

upcase!は、文字をすべて大文字に書き換えるメソッドです。はい、ちゃんとサーバー側のオブジェクトの実体(IDが21680810のオブジェクト)に変更が加えられていました。めでたし。

ところで、ここでちょっと疑問です。どうやらオブジェクトのIDを知っていることで、そのIDに紐付いたオブジェクトの実体を触れるようですが、いったいどのような仕組みになっているのでしょうか。仕組みを知るためにDRbServerのソースを見てみます。

# Convert a dRuby reference to the local object it refers to.
def to_obj(ref)
 return front if ref.nil?
 return front[ref.to_s] if DRbURIOption === ref
 @idconv.to_obj(ref)
end

ここで、今回関係ある部分は「@idconv.to_obj(ref)」です。@idconvは、デフォルトではDRbIdConvのインスタンスが設定されているようなので、このクラスを見ることにします。

class DRbIdConv

# Convert an object reference id to an object.
#
# This implementation looks up the reference id in the local object
# space and returns the object it refers to.
def to_obj(ref)
 ObjectSpace._id2ref(ref)
end
・・・

ここではObjectSpaceというものを使って変換しているようです。Rubyのリファレンスを見てみます。

ObjectSpace
全てのオブジェクトを操作するためのモジュール。

モジュール関数:
ObjectSpace._id2ref(id)
オブジェクト ID(Object#__id__)からオブジェクトを得ます。対応するオブジェクトが存在しなければ例外 RangeError が発生します。

Rubyリファレンスマニュアル - http://www.ruby-lang.org/ja/man/index.cgi?cmd=view;name=ObjectSpace

ObjectSpaceモジュールとは、どうやらRubyスクリプト内で実体化されたすべてのインスタンスの集合に対して色々できるやつのようです。なるほど、こういうやつが居るんですね。わかったので先へ進みます。

では、次はクライアントのirbから参照を渡します。ちゃんとstart_serviceしておきます。引数を指定しない場合、空いている適当なポート番号が割り当てられます。ここでは30273が割り当てられました。

[クライアント側]

irb(main):005:0> DRb.start_service
=> #<DRb::DRbServer:0x296448c ・・・・
irb(main):006:0> str = 'bar'
=> "bar"
irb(main):007:0> there[2] = DRbObject.new(str)
=> #<DRb::DRbObject:0x2937ce8 @ref=21696060, @uri="druby://クライアントのホスト名:30273">


そしてサーバー側で内容を書き換えます。

[サーバー側]

irb(main):012:0> h[2]
=> #<DRb::DRbObject:0x297898c @ref=21696060, @uri="druby://クライアントのホスト名:30273">
irb(main):013:0> h[2].upcase!
=> "BAR"

クライアント側の実体が書き換えられていることを確認します。

[クライアント側]

irb(main):008:0> str

=> "BAR"


はい、ちゃんと書き換えられていますね。最後に、ここでクライアントのirbを終わらせてから、クライアントが実体を持っている参照オブジェクトに対してサーバーから操作してみましょう。エラーになるはずです。

[サーバー側]

irb(main):014:0> h[2].to_s
DRb::DRbConnError: druby://クライアントのホスト名:30273 - #<Errno::EBADF: Bad file descriptor - connect(2)>

 DRbObjectについての理解がだいぶ深まったような気がします。なお、このエントリでは、本の中で紹介しているものとほぼ一緒の内容を試していますが、細かな手順が結構違っています。なのでこのエントリを読まれた方も是非一度、本の「4.1.2 dRubyでは?」に載っている手順に沿っておさらいしてみて下さい。次回はその続き、「4.2 自動的な参照渡し」に入るつもりです。

トラックバック

このエントリーのトラックバックURL:
http://www.grandnature.net/bin/mt-tb.cgi/67

コメント (42)

Thanks for an idea, you sparked at thought from a angle I hadn’t given thoguht to yet. Now lets see if I can do something with it.

I live in Hungary, and my provider is T-Mobile Hungary. Numbers are in the following format: country code, provider code, 7-digit number. Example: “+36301234567” (without quotes). Or, I can type 00 instead of the plus sign. Its the same. I tried these formats:

Terrific, that’s precisely what I was shooting for! You just saved me alot of searching around

Hi, Neat post. There's a problem with your website in internet explorer, would check this… IE still is the market leader and a large portion of people will miss your fantastic writing because of this problem.

I’m not sure where you are getting your information, but great topic. I needs to spend some time learning more or understanding more. Thanks for excellent information I was looking for this info for my mission.

I’d be inclined to come to terms with you on this. Which is not something I usually do! I enjoy reading a post that will make people think. Also, thanks for allowing me to comment!

Hey there! I know this is certainly somewhat off theme but I used to be questioning which blog platform are you using for this websites? I’m finding tired of Wordpress due to the fact I’ve had issues with hackers and I’m searching at alternatives for another platform. I might be awesome when you could position me in the direction of a superb platform.

hello blogger, I came across your site from yahoo answers and start reading several of one's other web site pages. They are great. Pls always keep it up… Ideal regards,

Effective day! Are you aware if they make any plugins to help with Search engine optimisation? I’m hoping to obtain my web site to rank for some targeted key terms but I’m not seeing very good gains. If you ever know of any make sure you reveal. A great many thanks!

hello there and thank you for your info – I have certainly picked up anything new from right here. I did however expertise several technical points using this web site, as I experienced to reload the website many times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will very frequently affect your placement in google and can damage your high-quality score if advertising and marketing with Adwords. Anyway I’m adding this RSS to my email and could look out for a lot more of your respective exciting content. Ensure that you update this again soon..

My programmer is wanting to persuade me to move to .net from PHP. I have always disliked the concept due to the fact that within the expenses. But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a year and am nervous about switching to another platform. I've heard superb items about blogengine.net. Is there a way I can import all my wordpress articles into it? Any kind of guidance will be actually appreciated!

I’m not sure where you're getting your information, but good topic. I needs to spend some time learning much more or understanding more. Thanks for excellent info I was looking for this information for my mission.

Hey very cool blog!! Man .. Excellent .. Amazing .. I'll bookmark your blog and take the feeds also…I am happy to find so many useful info here in the post, we need develop more strategies in this regard, thanks for sharing. . . . . .

Aw, this was a very nice post. In concept I want to put in writing like this moreover – taking time and actual effort to make an excellent article… but what can I say… I procrastinate alot and in no way seem to get something done.

I am extremely impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you customize it yourself? Either way keep up the excellent quality writing, it’s rare to see a nice blog like this one these days..

I work in web advertising at the product side, so it’s nice to be in a position acquire more perception into how affiliates are selecting their merchandise, though I strongly feel that you are uncommon one that takes under consideration the wants of their visitors.

Good post. I learn one thing more challenging on totally different blogs everyday. It would always be stimulating to learn content from different writers and practice slightly one thing from their store. I’d choose to use some with the content on my weblog whether or not you don’t mind. Natually I’ll give you a link on your net blog. Thanks for sharing.

As a Newbie, I'm always looking out online for articles that can help me. Thanks

Quite a comprehensive listing and makes for extraordinarily interesting reading… Expectantly will be able do it all though!!!

I’m really loving the contents of your blog. Hopefully you keep posting regularly. Thanks.

I’m really loving the contents of your blog. Hopefully you keep posting regularly. Thanks.

I’m really loving the contents of your blog. Hopefully you keep posting regularly. Thanks.

F*ckin’ awesome things here. I am very glad to see your article. Thanks a lot and i'm looking forward to contact you. Will you kindly drop me a mail?

Wow! what an idea ! What an idea ! Lovely .. Superb … :)

We're in powerful occasions these days, economic is pretty bad. To achieve visitors and readers, it’s really about putting high quality contents and fascinating articles.

golf:

Great list of ideas… I'm actually doing to have to think a cool animated film persona now! :)

WONDERFUL Post.thanks for share..more wait ..

Unbelievable article as at all times, I'm significantly considering something along the lines of an affiliate section by myself web site… so very timely post.

This is a very good tips especially to those new to blogosphere, brief and accurate information… Thanks for sharing this one. A must read article.

There's noticeably a bundle to find out about this. I assume you made certain nice points in features also.

Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

Great wordpress blog here.. It’s hard to find quality writing like yours these days. I really appreciate people like you! take care

my God, i thought you had been going to chip in with a few decisive insght on the end there, no longer depart it with ‘we go away it to you to determine’.

Hi, I will’t understand how you can add your website in my rss reader. ready to Assist me, please :)

I nonetheless don’t really feel the impacts on the web… real lifestyles - 100% affected

Hi, I will’t perceive how one can upload your website in my rss reader. able Assist me, please :)

I often don’t put up in Blogs however your weblog compelled me to, superb work.. beautiful …

my God, i believed you had been going to chip in with some decisive insght at the finish there, now not go away it with ‘we go away it to you to resolve’.

I like the way you talk about the hair. Also I just want to tell you that I'm newbie to blogging and definitely enjoyed your blog. Most likely I’m want to bookmark your blog post . You amazingly have fabulous stories. Thank you for sharing with us your website.

I love the way you are talking about the hair. Also I simply want to say I am very new to weblog and really enjoyed this blog. Very likely I’m likely to bookmark your blog post . You absolutely have tremendous stories. Bless you for revealing your website.

I see fairly a few associate marketers that shrink back from promoting excessive-price point products, thinking, “who’s going to wish to purchase that?”. I’m with you, although – it’s excellent idea to supply a wide variety products at completely different worth factors to enchantment to huge of consumers.

It’s actually a nice and useful piece of info. I’m glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

コメントを投稿

About

2007年10月24日 10:02に投稿されたエントリーのページです。

ひとつ前の投稿は「[番外]咳さんに褒められていた件」です。

次の投稿は「4章.参照渡しと値渡し (その6)」です。

他にも多くのエントリーがあります。メインページアーカイブページも見てください。