当函数返回其值时,似乎从 libffi 返回 double 数据类型的函数未正确转换,这是我使用的代码:
#include <stdio.h>
#include <stdlib.h>
#include <ffi.h>
#include <math.h> // The make call the function `cos` by the FFI.
int main()
{
ffi_cif cif;
ffi_type *args[1];
void *values[1];
ffi_arg rc;
args[0] = &ffi_type_double;
void *ptr = malloc(sizeof(double));
*((double *)ptr) = 3.0;
values[0] = ptr;
if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &ffi_type_double, args) == FFI_OK)
ffi_call(&cif, cos, &rc, values);
printf("%f\n", (double)rc);
return 0;
}
结果如下:13830464316077631000.000000
。
该ffi_arg
类型是 的别名unsigned long long
。文档说明ffi_arg
传递给ffi_call
函数的类型参数,如果它小于 ,则用于存储数据sizeof(ffi_arg)
,否则它是指向内存中数据的指针:
sizeof(ffi_arg)
对于非浮点类型,右值必须指向大于或等于的存储。对于较小的返回值类型, 必须使用ffi_arg
or整数类型来保存返回值。ffi_sarg
( https://manpages.debian.org/testing/libffi-dev/ffi_call.3.en.html )
所以我用指针取消引用尝试了它:
void* rc;
// The code to call the function and initialize the CIF...
double my_value = *(double *)((void *)rc);
这使程序崩溃了。
我应该如何访问使用rc
变量存储的值?
编辑 1
用于编译程序的命令行:
gcc source.c -lffi -o source
编译时没有错误或警告。
编辑 2
添加 `-Wall' 构建选项后,我得到:
warning: passing argument 2 of 'ffi_call' from incompatible pointer type [-Wincompatible-pointer-types]
ffi_call(&cif, cos, &rc, values);
^~~
这个警告似乎在libffi 示例中被忽略了。给出的示例对我来说非常有效(带有此警告)。