ffi_call.3 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. .Dd February 15, 2008
  2. .Dt ffi_call 3
  3. .Sh NAME
  4. .Nm ffi_call
  5. .Nd Invoke a foreign function.
  6. .Sh SYNOPSIS
  7. .In ffi.h
  8. .Ft void
  9. .Fo ffi_call
  10. .Fa "ffi_cif *cif"
  11. .Fa "void (*fn)(void)"
  12. .Fa "void *rvalue"
  13. .Fa "void **avalue"
  14. .Fc
  15. .Sh DESCRIPTION
  16. The
  17. .Nm ffi_call
  18. function provides a simple mechanism for invoking a function without
  19. requiring knowledge of the function's interface at compile time.
  20. .Fa fn
  21. is called with the values retrieved from the pointers in the
  22. .Fa avalue
  23. array. The return value from
  24. .Fa fn
  25. is placed in storage pointed to by
  26. .Fa rvalue .
  27. .Fa cif
  28. contains information describing the data types, sizes and alignments of the
  29. arguments to and return value from
  30. .Fa fn ,
  31. and must be initialized with
  32. .Nm ffi_prep_cif
  33. before it is used with
  34. .Nm ffi_call .
  35. .Pp
  36. .Fa rvalue
  37. must point to storage that is sizeof(ffi_arg) or larger for non-floating point
  38. types. For smaller-sized return value types, the
  39. .Nm ffi_arg
  40. or
  41. .Nm ffi_sarg
  42. integral type must be used to hold
  43. the return value.
  44. .Sh EXAMPLES
  45. .Bd -literal
  46. #include <ffi.h>
  47. #include <stdio.h>
  48. unsigned char
  49. foo(unsigned int, float);
  50. int
  51. main(int argc, const char **argv)
  52. {
  53. ffi_cif cif;
  54. ffi_type *arg_types[2];
  55. void *arg_values[2];
  56. ffi_status status;
  57. // Because the return value from foo() is smaller than sizeof(long), it
  58. // must be passed as ffi_arg or ffi_sarg.
  59. ffi_arg result;
  60. // Specify the data type of each argument. Available types are defined
  61. // in <ffi/ffi.h>.
  62. arg_types[0] = &ffi_type_uint;
  63. arg_types[1] = &ffi_type_float;
  64. // Prepare the ffi_cif structure.
  65. if ((status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI,
  66. 2, &ffi_type_uint8, arg_types)) != FFI_OK)
  67. {
  68. // Handle the ffi_status error.
  69. }
  70. // Specify the values of each argument.
  71. unsigned int arg1 = 42;
  72. float arg2 = 5.1;
  73. arg_values[0] = &arg1;
  74. arg_values[1] = &arg2;
  75. // Invoke the function.
  76. ffi_call(&cif, FFI_FN(foo), &result, arg_values);
  77. // The ffi_arg 'result' now contains the unsigned char returned from foo(),
  78. // which can be accessed by a typecast.
  79. printf("result is %hhu", (unsigned char)result);
  80. return 0;
  81. }
  82. // The target function.
  83. unsigned char
  84. foo(unsigned int x, float y)
  85. {
  86. unsigned char result = x - y;
  87. return result;
  88. }
  89. .Ed
  90. .Sh SEE ALSO
  91. .Xr ffi 3 ,
  92. .Xr ffi_prep_cif 3