cast filename to cdata pointer

22 views
Skip to first unread message

Alexander M.

unread,
Nov 17, 2016, 11:06:05 AM11/17/16
to python-cffi
Hi,

my intention is, to cast a script argument from:
sys.argv[1]

which is a str to a  char * cdata pointer. My library function only accepts cdata pointer.

Is there a possibility to cast this str object to such a pointer? 

Is there maybe a compatibility with ctypes?

Armin Rigo

unread,
Nov 18, 2016, 3:14:52 AM11/18/16
to pytho...@googlegroups.com
Hi Alexander,

On 17 November 2016 at 17:06, Alexander M. <skug...@gmail.com> wrote:
> my intention is, to cast a script argument from:
> sys.argv[1]
>
> which is a str to a char * cdata pointer. My library function only accepts
> cdata pointer.

Are you looking for ffi.new("char[]", sys.argv[1]) ?


Armin

Alexander M.

unread,
Nov 18, 2016, 3:40:04 AM11/18/16
to python-cffi
Yes, but this doesn't work, because the argument is a str object an the function only accepts a char pointer.

I could make it work by casting the str to bytes and then to a char array like this:

file = sys.argv[1]
file_name
=ffi.new("char[]",bytes(file,"utf-8"))
lib
.function(arg1,file_new)


Armin Rigo

unread,
Nov 18, 2016, 5:22:51 AM11/18/16
to pytho...@googlegroups.com
Hi again,

On 18 November 2016 at 09:40, Alexander M. <skug...@gmail.com> wrote:
> Yes, but this doesn't work, because the argument is a str object an the
> function only accepts a char pointer.

Ah, a Python 3 question then. The problem is then that you need a
"bytes" and not a unicode "str". You don't need ffi.new() at all;
it's unrelated to cffi. You need to encode the unicode string into
the suitable encoding, and "utf-8" is a good guess. If you need more
info, search for "bytes versus unicode strings in Python 3". Then you
simply write:

lib.function(arg1, sys.argv[1].encode("utf-8"))


A bientôt,

Armin.
Reply all
Reply to author
Forward
0 new messages