首先,您导入 ctypes 模块。然后,您需要加载包含上述函数的 c dll。之后,您需要设置该函数的参数类型和结果类型。最后,您创建目标缓冲区并调用您的函数。
Python:
import ctypes as ct
MAX_BUFSIZE = 100
mycdll = ct.CDLL("path_to_your_c_dll") # for windows you use ct.WinDLL(path)
mycdll.function_name.argtypes = [ct.c_char_p, ct.c_int,
ct.c_char_p, ct.c_char_p]
mycdll.function_name.restype = ct.c_int
mystrbuf = ct.create_string_buffer(MAX_BUFSIZE)
result = mycdll.function_name(mystrbuf, len(mystrbuf),
b"my_input", b"my_second_input")
使用 strncpy 的工作示例:
import ctypes as ct
MAX_BUFSIZE = 100
mycdll = ct.CDLL("libc.so.6") # on windows you use cdll.msvcrt, instead
mycdll.strncpy.argtypes = [ct.c_char_p, ct.c_char_p, ct.c_size_t]
mycdll.strncpy.restype = ct.c_char_p
mystrbuf = ct.create_string_buffer(MAX_BUFSIZE)
dest = mycdll.strncpy(mystrbuf, b"my_input", len(mystrbuf))
print(mystrbuf.value)
Python 3 输出:
user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python3 --version
Python 3.8.5
user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python3 python_ctypes.py
b'my_input'
Python 2 输出:
user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python2 --version
Python 2.7.18
user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python2 python_ctypes.py
my_input