Py_INCREF() incomprehension
Stefan Behnel
stefan_ml at behnel.de
Tue Apr 26 06:28:17 EDT 2011
Ervin Hegedüs, 26.04.2011 11:48:
> Hello Python users,
>
> I'm working on a Python module in C - that's a cryptographic module,
> which uses a 3rd-party lib from a provider (a bank).
> This module will encrypt and decrypt the messages for the provider web service.
>
> Here is a part of source:
>
> static PyObject*
> mycrypt_encrypt(PyObject *self, PyObject *args)
> {
> int cRes = 0;
> int OutLen = 0;
>
> char * url;
> char * path;
>
> if (!PyArg_ParseTuple(args, "ss",&url,&path)) {
Use the "s#" format instead to get the length as well.
> return NULL;
> }
>
> OutLen = strlen(url)*4;
> outdata=calloc(OutLen, sizeof(char));
>
> if (!outdata) {
> handle_err(UER_NOMEM);
I assume this raises MemoryError?
> return NULL;
> }
> cRes = ekiEncodeUrl (url, strlen(url)+1, outdata,&OutLen, 1, path);
>
> if (cRes == 0) {
> return Py_BuildValue("s", outdata);
You are leaking the memory allocated for outdata here.
And, again, use the "s#" format.
> } else {
> handle_err(cRes);
> return NULL;
> }
I assume this raises an appropriate exception?
> return Py_None;
This is unreachable code.
> where ekiEncodeUrl is in a 3rd-party library.
> I should call this function from Python like this:
>
> import mycrypt
>
> message = "PID=IEB0001&MSGT=10&TRID=000000012345678"
> crypted = mycrypt(mymessage, "/path/to/key");
>
> Everything works fine, but sorry for the recurrent question: where
> should I use the Py_INCREF()/Py_DECREF() in code above?
These two functions are not your problem here.
In any case, I recommend using Cython instead of plain C. It keeps you from
getting distracted too much by reference counting and other CPython C-API
details, so that you can think more about the functionality you want to
implement.
Stefan
More information about the Python-list
mailing list