错误的值,该函数返回双精度(libffi)

问题描述 投票:0回答:1

似乎从libffi返回双精度数据类型的函数在返回其值时未正确转换,这是我使用的代码:

#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),则用于存储数据,否则它是指向内存中数据的指针:

rvalue必须指向sizeof(ffi_arg)或更大的存储非浮点类型。对于较小的返回值类型,必须使用ffi_argffi_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 example中似乎忽略了此警告。给出的示例对我来说很好(带有此警告)。

c pointers double libffi
1个回答
0
投票

我认为您缺少问题中的某些信息,或者有关您的环境的信息有所不同。

我使用以下命令编译了代码

gcc source.c -lffi -lm -o source

并且还更改了

#include<libffi> 

#include<ffi.h>

使用这些更改和您的代码,我得到了答案13830464316077631488.000000。该问题似乎无法重现,但您可以尝试进行这些更改并在您的环境中进行尝试。

© www.soinside.com 2019 - 2024. All rights reserved.