フック (プログラミング)

フック: hook)は、プログラム中の特定の箇所に、利用者が独自の処理を追加できるようにする仕組みである。また、フックを利用して独自の処理を追加することを「フックする」という。

処理を追加できる箇所は、元のプログラムの開発者によって、あらかじめ決められている。初期化処理や入出力処理などの直前・直後が対象としてよく選ばれる。

主に元のプログラムに対する機能追加・拡張やカスタマイズの手段として使われるほか、デバッグのための情報収集にも有効である。このような有用な使い方の反面、既存のプログラムの動作を変更できることから、悪意を持ったプログラムによって利用される場合もある。例えばOSのキー入力処理のフックを使えばキーロガーを実装できることになる。

また、元のコードそのものは書き換えなくても動作を変更できることから、ROMで提供されるプログラムのバージョンアップや修正に使われることもある。ただしこの場合も、必要な個所に対応するフックがあらかじめ用意されていることが条件となる。すなわち、元のコードを設計する段階から、将来の機能拡張や修正を見越してフックを設計しておく必要がある。

実装例

フック用アドレスが定義されている例

8ビットパソコンのように機械語レベルの単純な制御が行われているシステムでは、フックとして呼出アドレスが定義されている。

例えばMSXの場合、ワークエリアの中に約100個のフック用アドレスが定義され、それぞれタイマ割り込みや各種入出力などに割り当てられている。フックは5バイト間隔で配置されており、初期状態ではRET(Z80におけるサブルーチンからの復帰命令)が書き込まれている。利用者はメモリ上の別の領域に独自の処理を配置し、フック用の5バイトには独自処理へのジャンプ命令を書き込む。

呼出先登録用のAPIが定義されている例

独自処理をプロシージャ関数として定義しておき、登録APIを使って登録する。現代の高級言語によるプログラミングでは、よく見られる実装形態である。

例えばMicrosoft Windowsの場合、OSが提供するフックには整数のIDが振られ、登録用関数SetWindowsHookExが提供されている。フックIDと独自処理への関数ポインタを引数としてSetWindowsHookEx関数を呼び出すと、フック処理として登録される。

フック用変数名や関数名が定義されている例

フックが変数名や関数名で定義されているシステムもある。インタプリタ型のシステムや、コンパイラ型でも利用者が記述した処理と一緒にリンケージエディタにかかる場合(ライブラリが提供するフックのように)などに見られる。

例えばテキストエディタGNU Emacsの場合、Emacs Lispという言語でさまざまな機能が記述されるが、大部分のEmacs Lispパッケージは変数名の末尾が「-hook」となる変数をフックとして定義している。GNU Emacs起動時にはemacs-startup-hookが、c-modeを呼び出した際にはc-mode-hookが評価されるといった具合である。LispプログラムはS式というリストになっており、変数にS式を設定しておけば、変数を評価する際にそのプログラムが実行される。

参考文献

  • ジェイムズ・ノーブル、チャールズ・ウィアー 著、安藤慶一 訳『省メモリプログラミング』(初版)ピアソン・エデュケーション、2002年6月20日(原著2001年)。ISBN 4-89471-408-6 

関連項目

Read other articles:

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Solarman – news · newspapers · books · scholar · JSTOR (September 2007) (Learn how and when to remove this message) Comics character SolarmanPublication informationPublisherPendulum Press (1979–1980)Marvel Comics (1989)Scout Comics (2016–2017)First appearanceP…

Kathleen Rice Kathleen Maura Rice (lahir 15 Februari 1965) adalah seorang jaksa dan anggota DPR Amerika Serikat. Ia berasal dari Partai Demokrat. Pranala luar Wikimedia Commons memiliki media mengenai Kathleen Rice. Congresswoman Kathleen Rice Diarsipkan 2021-01-07 di Wayback Machine. official U.S. House website Kathleen Rice for Congress Kathleen Rice di Curlie (dari DMOZ) Biografi di Biographical Directory of the United States Congress Catatan suara dikelola oleh The Washington Post Biografi, …

Pour les articles homonymes, voir Boyle. Robert BoylePortrait de Robert Boyle.BiographieNaissance 25 janvier 1627Lismore CastleDécès 31 décembre 1691 (à 64 ans)LondresSépulture St Martin-in-the-FieldsÉpoque Génération du XVIIe siècle (d)Nationalité IrlandaisDomiciles Comté de Waterford, AngleterreFormation Collège d'Eton (à partir de 1635)Activités Physicien, chimiste, philosophePère Richard BoyleMère Catherine Fenton BoyleFratrie Richard BoyleKatherine Jones (en)Roger Boyle…

Party groupings. The Environmental Integrity Group (EIG) is a negotiation group consisting of 6 parties to the UNFCCC. When it was formed in 2000, it only consisted of Switzerland, Korea, and Mexico.[1] History The Environmental Integrity Group was initiated by Switzerland during the negotiations of the Kyoto Protocol, where only party groups were allowed to negotiate. Switzerland was not part of any group and they did not want to join the Umbrella Group. So Switzerland declared to form …

Naval gun Cannone da 152/45 Cannone da 152/45's on pedestal mounts at the Ansaldo factory.TypeNaval gunCoastal artillerySiege gunPlace of originKingdom of ItalyService historyIn service1917-1945Used byKingdom of ItalyWarsWorld War IWorld War IIProduction historyManufacturerAnsaldoSpecificationsMassNaval gun: 7.1 t (7 long tons)Siege gun: 16.67 t (16.41 long tons)Barrel length7.138 m (23 ft 5 in) L/46.7ShellSeparate loading bagged charge and proje…

Painting by Gustav Klimt Water Serpents IIArtistGustav KlimtYear1904–1907MediumOil on canvasDimensions80 cm × 145 cm (31 in × 57 in)LocationPrivate collection, Asia Water Serpents II, also referred to as Wasserschlangen II, is an oil painting made by Gustav Klimt in 1907. It is the follow-up painting to the earlier painting Water Serpents I. Like the first painting, Water Serpents II deals with the sensuality of women's bodies and same-sex relationsh…

2020年夏季奥林匹克运动会波兰代表團波兰国旗IOC編碼POLNOC波蘭奧林匹克委員會網站olimpijski.pl(英文)(波兰文)2020年夏季奥林匹克运动会(東京)2021年7月23日至8月8日(受2019冠状病毒病疫情影响推迟,但仍保留原定名称)運動員206參賽項目24个大项旗手开幕式:帕维尔·科热尼奥夫斯基(游泳)和马娅·沃什乔夫斯卡(自行车)[1]闭幕式:卡罗利娜·纳亚(皮划艇)[2…

Town in Greater Manchester, England Human settlement in EnglandSaleSale Town HallSaleLocation within Greater ManchesterPopulation54,515 (2021 census)[1]OS grid referenceSJ785915• London162 mi (261 km) SEMetropolitan boroughTraffordMetropolitan countyGreater ManchesterRegionNorth WestCountryEnglandSovereign stateUnited KingdomPost townSALEPostcode districtM33Dialling code0161PoliceGreater ManchesterFireGreater ManchesterAmbulanceNor…

Intermittent stream in Galilee, Israel Nahal Dishon Wet Nahal Dishon The Dishon Stream (Hebrew: נחל דישון, Nahal Dishon) is an intermittent stream/wadi in Upper Galilee, Israel. It is 26 kilometers long, starts on the eastern slope of Mount Meron and drains into the Jordan River in the area of the drained Hula Lake [he]. It is one of the largest streams in East Upper Galilee. Its name is a modification of the name of the depopulated Palestinian village of Dayshum.[1]…

Cari artikel bahasa  Cari berdasarkan kode ISO 639 (Uji coba)   Cari berdasarkan nilai Glottolog   Kolom pencarian ini hanya didukung oleh beberapa antarmuka Halaman rumpun acak Rumpun bahasaTsouikPersebaranTaiwan bagian tengahPenggolongan bahasaAustronesia(Formosa)Tsouik Tsou Tsouik Selatan Kode bahasaLinguasfer30-EAGlottolognonetsou1248  (Tsou)kana1292  (Kanakanavu–Saaroa)Lokasi penuturan(kuning) Tsouik Raya  Portal BahasaSunting kotak info • L • B…

بيشباغير الإحداثيات 45°02′00″N 42°38′00″E / 45.03333333°N 42.63333333°E / 45.03333333; 42.63333333   تقسيم إداري  البلد روسيا  تعديل مصدري - تعديل   يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يم…

Молочная кислота Общие Систематическоенаименование 2-​гидроксипропановая кислота Традиционные названия Молочная кислота Хим. формула CH3CH(OH)COOH Рац. формула C3H6O3 Физические свойства Молярная масса 90,08 г/моль Термические свойства Температура  • кипения 122 °C Хи…

Santo PausPaulus VIAwal masa kepausan21 Juni 1963Akhir masa kepausan6 Agustus 1978PendahuluYohanes XXIIIPenerusYohanes Paulus IImamatTahbisan imam29 Mei 1920oleh Giacinto GaggiaTahbisan uskup12 Desember 1954oleh Eugène TisserantPelantikan kardinal15 Desember 1958oleh Yohanes XXIIIInformasi pribadiNama lahirGiovanni Battista Enrico Antonio Maria MontiniLahir26 September 1897Concesio, ItaliaWafat6 Agustus 1978Castel Gandolfo, ItaliaJabatan sebelumnyaReferendary Prelate of Apostolic Sign…

Hunger WarPart of the Polish–Teutonic WarsDateSummer 1414LocationState of the Teutonic OrderResult Mediation at the Council of ConstanceBelligerents  Kingdom of Poland Grand Duchy of Lithuania  Teutonic StateCommanders and leaders JogailaVytautas Michael Küchmeister von SternbergvteGerman–Polish WarsHoly Roman Empire 963 967 972 979 1003-1018 1028-1031 1074 1109 1146 1157 1184 1278 Brandenburg 1247-1252 1265-1278 1269-1272 1296 1311-1312 1316 1326-1329 1370 1476-1482 1656-165…

Brand of ice cream and frozen dessert products For the meat company, see Wall's (meat). Wall'sProduct typeIce creamFrozen dessertOwnerUnileverCountryUnited KingdomIntroduced1922; 102 years ago (1922)Related brandsWall's (meat)Tagline Goodbye Serious Semua Jadi Happy(Everyone's Happy, Indonesia only) Websitewww.wallsicecream.com/uk/home.html Wall's is an ice cream and frozen dessert brand in the United Kingdom owned by Unilever and is part of the Heartbrand global frozen dessert…

لانغنتسن    شعار   الإحداثيات 49°29′40″N 10°47′41″E / 49.494444444444°N 10.794722222222°E / 49.494444444444; 10.794722222222   [1] تقسيم إداري  البلد ألمانيا[2][3]  التقسيم الأعلى منطقة فورت  خصائص جغرافية  المساحة 46.33 كيلومتر مربع (31 ديسمبر 2017)[4]  ارتفاع 313 متر  …

Ceylonese lawyer and politician This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Fredrick de Silva – news · newspapers · books · scholar · JSTOR (November 2017) (Learn how and when to remove this message) Hon.Fredrick de SilvaMBECeylon Ambassador to France and UNESCOMember of the Ceylon Parliamentfor KandyIn off…

系列条目保守主义 分支 激情保守主义(英语:Compassionate conservatism) 保守统合主义(英语:Conservative corporatism) 保守社会主义 文化保守主義 保守女权主义(英语:List of conservative feminisms) 財政保守主義 綠色保守主義 自由保守主義 保守自由主義 自由意志保守主義 民族保守主義 新保守主義 新右派 旧保守主义 家长保守主义 实用保守主义(英语:Pragmatic conservatism) 进步保…

Map of Washington's 45th legislative district Washington's 45th legislative district is one of 49 electoral districts in Washington state for representation in the state legislature. It extends from Kirkland on the west, Duvall on the east, and Sammamish on the south.[1] The district's legislators are state senator Manka Dhingra and state representatives Roger Goodman (position 1) and Larry Springer (position 2), all Democrats.[2] On November 7, 2017, there was a special election…

In this Spanish name, the first or paternal surname is Ortega and the second or maternal family name is Lara. José Antonio Ortega Lara in 2014 José Antonio Ortega Lara (born 1958 in Montuenga es, parish of Madrigalejo del Monte, Burgos) is one of the founders of the Spanish political party Vox.[1] He is also a former Spanish prison officer who was kidnapped by the terrorist organization ETA for 532 days between 1996 and 1997. Additionally, he was a member of the People's Party …