使用 ctypes 将字符串作为 char 指针数组传递

Pass a string as a char pointer array using ctypes

我有这个签名的C函数:

int fileopen(const char *fname, int flags)

在Linux系统中,我想使用ctypes从Python传递fname所以我使用ctypes.c_char_p("file1.dat")如下:

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)

但是我得到这个错误:

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

除了使用 ctypes.c_char_p,我不知道还有什么方法可以传递字符串 "file1.dat"。如何解决这个问题呢?

谢谢

"file1.dat" 更改为 b"file1.dat"(与 'file1.dat'.encode('ascii') 相同)。