我想从Python调用一个C函数,并传递一个包含可变字符串数组的结构。
C函数应该将其结果写入数组。
然而,在调用C函数之前,Python程序崩溃了。
以下是重现此问题的最小示例:
from ctypes import *
LINE_COUNT = 100
MAX_LINE_LENGTH = 30
class ExchangeStructure(Structure):
_fields_ = [("results", LINE_COUNT * POINTER(c_char * MAX_LINE_LENGTH))]
def createExchangeStructure():
exchange_structure = ExchangeStructure()
results = []
for i in range(LINE_COUNT):
results.append(create_string_buffer(MAX_LINE_LENGTH))
results_as_C_array = (LINE_COUNT * (c_char * MAX_LINE_LENGTH))(*results)
exchange_structure.results = pointer(results_as_C_array)
def main():
createExchangeStructure()
if __name__ == '__main__':
main()
C结构如下所示:
struct Response {
...
char* results[LINE_COUNT];
...
};
它在函数createExchangeStructure的最后一行崩溃,并显示以下错误消息:
TypeError: incompatible types, LP_c_char_Array_30_Array_100 instance instead of LP_c_char_Array_30_Array_100 instance
我该如何解决这个问题?