Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a string as a char pointer array using ctypes

I have a C function of this signature:

int fileopen(const char *fname, int flags)

In Linux system, I want to pass the fname from Python using ctypes so I use ctypes.c_char_p("file1.dat") as the following:

import ctypes as ctypes

dll_name = "IO/pyaio.so"
dllabspath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + dll_name
pyaio = ctypes.CDLL(dllabspath)

fd_w = pyaio.fileopen(ctypes.c_char_p("file1.dat"), 1)

But I get this error:

Traceback (most recent call last):
  File "test.py", line 21, in <module>
    fd_w = pyaio.fileopen(ctypes.c_char_p("file1.dat"), 1) # 0 read, 1 write
TypeError: bytes or integer address expected instead of str instance

I don't know another way to pass the string"file1.dat" than using ctypes.c_char_p. How to solve this problem?

Thank you

like image 916
steve Avatar asked Oct 26 '25 03:10

steve


1 Answers

Change "file1.dat" to b"file1.dat" (which is the same you would get with 'file1.dat'.encode('ascii')).

like image 167
fferri Avatar answered Oct 28 '25 17:10

fferri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!