Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #102776 > unrolled thread

Re: Copying void * string to

Started byeryk sun <eryksun@gmail.com>
First post2016-02-10 18:23 -0600
Last post2016-02-10 18:23 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Copying void * string to eryk sun <eryksun@gmail.com> - 2016-02-10 18:23 -0600

#102776 — Re: Copying void * string to

Fromeryk sun <eryksun@gmail.com>
Date2016-02-10 18:23 -0600
SubjectRe: Copying void * string to
Message-ID<mailman.23.1455150247.22075.python-list@python.org>
On Wed, Feb 10, 2016 at 6:07 AM, Martin Phillips
<martinphillips@ladybridge.com> wrote:
>
> Several functions in the C library return pointers to dynamically allocated w_char null
> terminated strings. I need to copy the string to a Python variable and call an existing
> library function that will free the dynamically allocate memory.
>
> My test code for this is
>
> def Test(fno, item):
>     func = mylib. MyFunc
>     func.restype = ct.c_void_p
>     s = func(fno, item)
>     result = s
>     mylib.free(s)
>     return result
>
> The problem is with the line that sets the result variable. I need this to make a copy of
> the dynamically allocated string, not the pointer to it.

There are several options, but I think the simplest is to use a
subclass of ctypes.c_wchar_p. subclasses of simple types don't get
converted automatically. Copy the string using the "value" attribute.
Then free() the pointer. But only copy and free the result if it isn't
NULL (i.e. a false boolean value).

    import ctypes

    mylib = ctypes.CDLL('path/to/mylib')

    class MyLibError(Exception):
        pass

    class my_wchar_p(ctypes.c_wchar_p):
        pass

    mylib.MyFunc.restype = my_wchar_p

    def test(fno, item):
        s = mylib.MyFunc(fno, item)
        if s:
            result = s.value
            mylib.free(s)
            return result
        raise MyLibError('mylib.MyFunc returned NULL')

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web