您可以使用分配缓冲区,
ctypes并将其分配给指针。一旦Python ctypes对象没有引用,它们将被自动释放。这是一个简单的示例(带有Windows
DLL …没有方便的Linux机器,但是想法是一样的)和Python包装器。
create_string_buffer分配的可写缓冲器,可以在Python被传递至C这
ctypes将编组作为一个
char*。
您还可以
ctypes使用以下语法创建类型的可写数组:
variable_name = (ctypes_type * length)(initial_values)
h
#ifdef DLL_EXPORTS#define DLL_API __declspec(dllexport)#else#define DLL_API __declspec(dllimport)#endifstruct example { char* data; int len; // of data buffer double* doubles; int count; // of doubles};DLL_API void func(struct example* p);c
#include <stdio.h>#define DLL_EXPORTS#include "x.h"void func(struct example* p){ int i; strcpy_s(p->data,p->len,"hello, world!"); for(i = 0; i < p->count; i++) p->doubles[i] = 1.1 * (i + 1);}x.py
import ctypesclass Example(ctypes.Structure): _fields_ = [ ('data',ctypes.POINTER(ctypes.c_char)), ('len',ctypes.c_int), ('doubles',ctypes.POINTER(ctypes.c_double)), ('count',ctypes.c_int)] def __init__(self,length,count): self.data = ctypes.cast(ctypes.create_string_buffer(length),ctypes.POINTER(ctypes.c_char)) self.len = length self.doubles = (ctypes.c_double * count)() self.count = count def __repr__(self): return 'Example({},[{}])'.format( ctypes.string_at(self.data), ','.join(str(self.doubles[i]) for i in range(self.count)))class Dll: def __init__(self): self.dll = ctypes.CDLL('x') self.dll.func.argtypes = [ctypes.POINTER(Example)] self.dll.func.restype = None def func(self,ex): self.dll.func(ctypes.byref(ex))d = Dll()e = Example(20,5)print('before:',e)d.func(e)print ('after:',e)输出量
before: Example(b'',[0.0,0.0,0.0,0.0,0.0])after: Example(b'hello, world!',[1.1,2.2,3.3000000000000003,4.4,5.5])



