0

私は Python C API を使用しており、いくつかの C++ クラスで使用する PyTypeObjects の新しいインスタンスを割り当てる関数を作成しようとしています。アイデアは、各クラスが、このファクトリでインスタンス化される PyTypeObject へのポインタを持つことです。ポインターは静的でなければなりません。ただし、このアプローチには問題があります。

  1. PyTypeObject へのポインタを含むクラスで、その静的変数をファクトリ関数 (別のクラスにありますが静的) の結果と等しくなるように設定しようとすると、「undefined reference」リンカ エラーが発生します。関数は実行時まで発生しないため、これは理にかなっていると思いますが、これを行う別の方法がわかりません。
  2. 最初のフィールドは常にマクロである PyObject_VAR_HEAD であるため、PyTypeObject フィールドを動的に設定する方法がわかりません。

これが理にかなっていることを願っています。基本的に、いくつかのクラスが PyTypeObject を静的に再定義する必要がなく、代わりにファクトリ関数から PyTypeObject 変数をインスタンス化できるようにしようとしています。

4

1 に答える 1

0

Try this: create a 'template' PyTypeObject, and use struct copying (or memcpy) to clone the basic template. Then you can fill it in with the requisite field definitions after that. This solves (2), since you only have to declare the full PyTypeObject once.

For your first point, you just set the static variable from your module init instead of doing it in the static variable declaration. So, it won't be set until your module actually initializes.

If you plan on doing this often, it may be worth looking at Boost::Python, which simplifies the process of generating CPython wrappers from C++ classes.

于 2012-08-23T19:26:03.910 に答える