LoginSignup
1
1

More than 3 years have passed since last update.

pybind11 で C++ から Python オブジェクトの変数やメソッドにアクセスするメモ

Last updated at Posted at 2021-04-09

背景

C++ 側で, ちょっとした Python クラス(自作, 標準ライブラリ, etc)のインスタンスにアクセスしたいときがある. C++ 側で毎回バインディングを書くほどのものではないもの.

方法

モジュールもいけます.

基本は py::object で扱って attr("attrname") で変数, メソッドにアクセスして実現すればいけます!


class MyClass:
  def __init__(self):
    self.index = 42


py::object o = ... ; // MyClass なもの

py::print(o.attr("index"));

明示的に型が必要であれば cast を用います.

py::print(o.attr("index").cast<int>());

hasattr

オブジェクトが, 指定するメソッドや変数を持っているかどうかは pybind11::hasattr で確認できます.

py::print(pybind11::hasattr(o, "index"));

// NG: インスタンス側のメソッドとしては定義されていないので注意
o.hasattr("index");

contains

Python 側のクラスが __contains__ を定義していれば, o.contains(key) が使えます.

setattr 相当

o.attr["name"] = ...

でいけます.

TODO

  • 主にデータ構造を受け渡ししたい場合, あまりデータ構造が複雑でなければ, 一旦 dict(py::dict) にして C++ <-> Python でやりとりしたほうがよさそう
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1