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

ste*_*eve 4 python ctypes python-3.x

我有C这个签名的功能:

int fileopen(const char *fname, int flags)

在Linux系统中,我想fname使用Python传递,ctypes所以我使用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)
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

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
Run Code Online (Sandbox Code Playgroud)

"file1.dat"除了使用 之外,我不知道还有其他传递字符串的方法ctypes.c_char_p。如何解决这个问题呢?

谢谢

ffe*_*rri 5

更改"file1.dat"b"file1.dat"(与使用 得到的结果相同'file1.dat'.encode('ascii'))。