小编Art*_*rty的帖子

传输bytearray从Python到C并返回它

我需要快速处理XOR bytearray,在Python的变种中

for i in range(len(str1)): str1[i]=str1[i] ^ 55
Run Code Online (Sandbox Code Playgroud)

工作很慢
我在C中写了这个模块.我知道C语言非常糟糕,在我写之前什么也没写.
在一个变种中

PyArg_ParseTuple (args, "s", &str))
Run Code Online (Sandbox Code Playgroud)

一切都按预期工作,但我需要使用而不是ss*因为元素可以包含embeded null,但如果我在调用python崩溃时将s更改为s*

PyArg_ParseTuple (args, "s*", &str)) // crash
Run Code Online (Sandbox Code Playgroud)

也许像我这样的初学者想用我的例子作为开始写自己的东西,所以把这个例子中的所有信息都带到Windows上.
http://docs.python.org/dev/c-api/arg.html页面上解析参数和构建值

test_xor.c

#include <Python.h>

static PyObject* fast_xor(PyObject* self, PyObject* args)
{
    const char* str ;
    int i;

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

    for(i=0;i<sizeof(str);i++) {str[i]^=55;};
    return Py_BuildValue("s", str);

}

static PyMethodDef fastxorMethods[] =
{
     {"fast_xor", fast_xor, METH_VARARGS, "fast_xor desc"},
     {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC

initfastxor(void)
{
     (void) Py_InitModule("fastxor", fastxorMethods);
}
Run Code Online (Sandbox Code Playgroud)

test_xor.py

import …
Run Code Online (Sandbox Code Playgroud)

c python

5
推荐指数
3
解决办法
6579
查看次数

标签 统计

c ×1

python ×1