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

时间:2022-09-06 18:46:19

I have a C function of this signature:

我有这个签名的C函数:

int fileopen(const char *fname, int flags)

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:

在Linux系统中,我想使用ctype从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)

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?

我不知道另一种传递字符串“file1”的方法。比使用ctypes.c_char_p dat”。如何解决这个问题?

Thank you

谢谢你!

1 个解决方案

#1


2  

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

改变“file1。dat file1“b”。dat(与“file1.dat”.encode(“ascii”)相同。

#1


2  

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

改变“file1。dat file1“b”。dat(与“file1.dat”.encode(“ascii”)相同。