Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A few comments on your code to help improve it, IMHO. There are functions provided by the python C API that do exactly what you need to do, and make sure everything conforms to the Python way of doing things. It will handle embedded NULL's without a problem.</p> <p>Rather than calling <code>malloc</code> directly, change this:</p> <pre><code>cdef char *ciphertext = &lt;char *&gt;malloc(src_len) </code></pre> <p>to</p> <pre><code>cdef str retval = PyString_FromStringAndSize(PyString_AsString(source), &lt;Py_ssize_t&gt;src_len) cdef char *ciphertext = PyString_AsString(retval) </code></pre> <p>The above lines will create a brand new Python str object initialized to the contents of <code>source</code>. The second line points <code>ciphertext</code> to <code>retval</code>'s internal <code>char *</code> buffer without copying. Whatever modifies <code>ciphertext</code> will modify <code>retval</code>. Since <code>retval</code> is a brand new Python str, it can be modified by C code before being returned from <code>_real_encrypt</code>.</p> <p>See the Python C/API docs on the above functions for more details, <a href="http://docs.python.org/c-api/string.html#PyString_FromStringAndSize" rel="nofollow">here</a> and <a href="http://docs.python.org/c-api/string.html#PyString_AsString" rel="nofollow">here</a>.</p> <p>The net effect saves you a copy. The whole code would be something like:</p> <pre><code>cdef extern from "Python.h": object PyString_FromStringAndSize(char *, Py_ssize_t) char *PyString_AsString(object) def _real_encrypt(self, source): src_len = len(source) cdef str retval = PyString_FromStringAndSize(PyString_AsString(source), &lt;Py_ssize_t&gt;src_len) cdef char *ciphertext = PyString_AsString(retval) cmc.mcrypt_generic_init(self._mcStream, &lt;void *&gt;self._key, len(self._key), NULL) cmc.mcrypt_generic(self._mcStream, &lt;void *&gt;ciphertext, src_len) # since the above initialized ciphertext, the retval str is also correctly initialized, too. cmc.mcrypt_generic_deinit(self._mcStream) return retval </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload