4

私は Python ( 2.6 ) 拡張機能を作成していますが、不透明なバイナリ BLOB (null バイトが埋め込まれている) を拡張機能に渡す必要がある状況があります。

ここに私のコードのスニペットがあります:

from authbind import authenticate

creds = 'foo\x00bar\x00'
authenticate(creds)

以下をスローします。

TypeError: argument 1 must be string without null bytes, not str

authbind.cc の一部を次に示します。

static PyObject* authenticate(PyObject *self, PyObject *args) {

    const char* creds;

    if (!PyArg_ParseTuple(args, "s", &creds))
        return NULL;
}

これまでのところ、ブロブを のような生の文字列として渡そうとしましたcreds = '%r' % credsが、文字列の周りに引用符が埋め込まれているだけでなく、\x00バ​​イトをリテラル文字列表現に変換します。

どうすれば必要なことを達成できますか? yy#およびPyArg_ParseTuple() 形式の文字については 3.2 で知っていy*ますが、2.6 に限定されています。

4

1 に答える 1

4

わかりました、私はこのリンクの助けを借りてを理解しました。

私は次のようなPyByteArrayObject(ドキュメントはこちら)を使用しました:

from authbind import authenticate

creds = 'foo\x00bar\x00'
authenticate(bytearray(creds))

そして、拡張コードで:

static PyObject* authenticate(PyObject *self, PyObject *args) {

    PyByteArrayObject *creds;

    if (!PyArg_ParseTuple(args, "O", &creds))
        return NULL;

    char* credsCopy;
    credsCopy = PyByteArray_AsString((PyObject*) creds);
}

credsCopy必要に応じて、バイトの文字列を保持するようになりました。

于 2012-12-18T15:56:38.970 に答える