From 762491db822570e20090d6ba1cdec16ae2845397 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Fri, 26 Apr 2024 18:08:32 +0900 Subject: [PATCH] [DOC] Caveat about "allocate then wrap" --- doc/extension.ja.rdoc | 5 +++++ doc/extension.rdoc | 11 ++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/doc/extension.ja.rdoc b/doc/extension.ja.rdoc index 48699ac620..2f7856f3d4 100644 --- a/doc/extension.ja.rdoc +++ b/doc/extension.ja.rdoc @@ -784,6 +784,11 @@ RUBY_TYPED_WB_PROTECTED :: GC}[rdoc-ref:@Appendix+D.+-E4-B8-96-E4-BB-A3-E5-88-A5GC] も参照してください. +このマクロは例外を発生させる可能性があることに注意してくださ +い. ラップされる sval が,解放する必要があるリソース (割り +当てられたメモリ,外部ライブラリからのハンドルなど) を保持し +ている場合は,rb_protect を使用する必要があります. + Cの構造体の割当と対応するオブジェクトの生成を同時に行うマク ロとして以下のものが提供されています. diff --git a/doc/extension.rdoc b/doc/extension.rdoc index 01ac140e69..ba59d107ab 100644 --- a/doc/extension.rdoc +++ b/doc/extension.rdoc @@ -759,7 +759,12 @@ RUBY_TYPED_FROZEN_SHAREABLE :: If this flag is not set, the object can not become a shareable object by Ractor.make_shareable() method. -You can allocate and wrap the structure in one step. +Note that this macro can raise an exception. If sval to be wrapped +holds a resource needs to be released (e.g., allocated memory, handle +from an external library, and etc), you will have to use rb_protect. + +You can allocate and wrap the structure in one step, in more +preferable manner. TypedData_Make_Struct(klass, type, data_type, sval) @@ -768,6 +773,10 @@ the structure, which is also allocated. This macro works like: (sval = ZALLOC(type), TypedData_Wrap_Struct(klass, data_type, sval)) +However, you should use this macro instead of "allocation then wrap" +like the above code if it is simply allocated, because the latter can +raise a NoMemoryError and sval will be memory leaked in that case. + Arguments klass and data_type work like their counterparts in TypedData_Wrap_Struct(). A pointer to the allocated structure will be assigned to sval, which should be a pointer of the type specified.