0

データを準備するためにpython(手段) を使用していくつかの実験を行う(また、それらを有線に送信する - SPI) ことは、遅い (システムが限られている) ことを示しています。そこで、重要な部分を延期するために、組み込みpython3の拡張モジュールを作成することを考えていました。C次のいずれかを希望します。

  • pythonスクリプトは、拡張モジュールで作成されたメモリ ブロックにアクセスでき、できれmalloc()ば透過的に変換できます。bytearray
  • 拡張モジュールは、できれば透過的に変換可能bytearrayで作成されたオブジェクトへのポインターを取得しますpythonvoid *

python目標は、 (as としてbytearray) と拡張モジュール (asとして)の両方からアクセスできるゼロ変換メモリ ブロックとしてもゼロ コピーを持つことですvoid *

これを達成する方法はありますか?

4

1 に答える 1

0

OK、予想よりも簡単なようです ;-)

  • bytearray基盤となるメモリ ブロックへのアクセスを直接サポートします。これはまさに必要なものです。
  • bytearray関数呼び出しの引数リストからオブジェクトを抽出するための書式指定子があります

C 拡張モジュール [ test.c]:

#include <Python.h>
#include <stdint.h>

/* Forward prototype declaration */
static PyObject *transform(PyObject *self, PyObject *args);

/* Methods exported by this extension module */
static PyMethodDef test_methods[] =
{
     {"transform", transform, METH_VARARGS, "testing buffer transformation"},
     {NULL, NULL, 0, NULL}
};


/* Extension module definition */
static struct PyModuleDef test_module =
{
   PyModuleDef_HEAD_INIT,
   "BytearrayTest",
   NULL,
   -1,
   test_methods,
};


/* 
 * The test function 
 */
static PyObject *transform(PyObject *self, PyObject *args)
{
    PyByteArrayObject *byte_array;
    uint8_t           *buff;
    int                buff_len = 0;
    int                i;


    /* Get the bytearray object */
    if (!PyArg_ParseTuple(args, "Y", &byte_array))
        return NULL;

    buff     = (uint8_t *)(byte_array->ob_bytes); /* data   */
    buff_len = byte_array->ob_alloc;              /* length */

    /* Perform desired transformation */
    for (i = 0; i < buff_len; ++i)
        buff[i] += 65;

    /* Return void */
    Py_INCREF(Py_None);
    return Py_None;
}


/* Mandatory extension module init function */
PyMODINIT_FUNC PyInit_BytearrayTest(void)
{
    return PyModule_Create(&test_module);
}

C 拡張モジュールのビルド/デプロイ スクリプト [ setup.py]:

#!/usr/bin/python3
from distutils.core import setup, Extension

module = Extension('BytearrayTest', sources = ['test.c'])

setup (name = 'BytearrayTest',
       version = '1.0',
       description = 'This is a bytearray test package',
       ext_modules = [module])

拡張モジュールをビルド/インストールします。

# ./setup.py build
# ./setup.py install

試して:

>>> import BytearrayTest
>>> a = bytearray(16); a
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> BytearrayTest.transform(a); a
bytearray(b'AAAAAAAAAAAAAAAA')
>>>
于 2016-12-04T15:47:31.033 に答える