我正在尝试将以下C标头转换为等效的Delphi版本:
/** pointer to a malloc function, supporting client overriding memory
* allocation routines */
typedef void * (*yajl_malloc_func)(void *ctx, unsigned int sz);
/** pointer to a free function, supporting client overriding memory
* allocation routines */
typedef void (*yajl_free_func)(void *ctx, void * ptr);
/** pointer to a realloc function which can resize an allocation. */
typedef void * (*yajl_realloc_func)(void *ctx, void * ptr, unsigned int sz);
typedef struct
{
/** pointer to a function that can allocate uninitialized memory */
yajl_malloc_func malloc;
/** pointer to a function that can resize memory allocations */
yajl_realloc_func realloc;
/** pointer to a function that can free memory allocated using
* reallocFunction or mallocFunction */
yajl_free_func free;
/** a context pointer that will be passed to above allocation routines */
void * ctx;
} yajl_alloc_funcs;
我的Delphi代码目前看起来像这样:
Tyajl_malloc_func = function(context: pointer; sizeOf: Cardinal): Pointer of Object; cdecl;
Tyajl_free_func = procedure(context: pointer; ptr: Pointer) of Object; cdecl;
Tyajl_realloc_func = function(context: pointer; ptr: Pointer; sizeOf: cardinal): Pointer of Object; cdecl;
yajl_alloc_funcs = record
malloc: Tyajl_malloc_func;
free: Tyajl_free_func;
realloc: Tyajl_realloc_func;
ctx: pointer;
end;
问题是我很确定我正在对这些做错,因为我无法记住如何获得指向这两个函数的指针。我的问题是:当我尝试将其分配给yajl_alloc_funcs.malloc时,如何获取指向malloc函数的指针?
或者,如果我在翻译中做错了什么,这里的“正确”方法是什么?
更新:对于我的要求似乎有些混乱。我已经实现了实际的方法,并尝试使用上述记录使用以下代码将它们提供给DLL:
var
alloc_funcs: yajl_alloc_funcs;
begin
FillChar(alloc_funcs, SizeOf(alloc_funcs), #0);
alloc_funcs.malloc := yajl_malloc;
alloc_funcs.free := yajl_free;
alloc_funcs.realloc := yajl_realloc;
..
这给了我一个错误: E2009不兼容的类型:'常规过程和方法指针' 我怀疑是因为我在标题翻译中做错了。
非常感谢任何帮助。
答案 0 :(得分:4)
不要使用“对象” - 这与此无关。
更新:哪行代码会出错?我无法想象,下一个代码编译并按预期工作:
type
Tyajl_malloc_func = function(context: pointer; sizeOf: Cardinal): Pointer; cdecl;
Tyajl_free_func = procedure(context: pointer; ptr: Pointer); cdecl;
Tyajl_realloc_func = function(context: pointer; ptr: Pointer; sizeOf: cardinal): Pointer; cdecl;
Tyajl_alloc_funcs = record
malloc: Tyajl_malloc_func;
free: Tyajl_free_func;
realloc: Tyajl_realloc_func;
ctx: pointer;
end;
function yajl_malloc_func(context: pointer; sizeOf: Cardinal): Pointer; cdecl;
begin
Result:= Pointer($1234);
end;
var
yajl_alloc_funcs: Tyajl_alloc_funcs;
procedure TForm1.Button1Click(Sender: TObject);
begin
yajl_alloc_funcs.malloc:= yajl_malloc_func;
ShowMessage(Format('%p', [yajl_alloc_funcs.malloc(nil, 0)]));
end;
答案 1 :(得分:0)
您现在需要定义传递给此C库的名为malloc free和realloc的函数。您可以通过调用GetMem,FreeMem和ReallocMem在Delphi中实现它们。