pmm  1.0.0
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros
executor_test.c
Go to the documentation of this file.
1 /*
2  * Contains rough code for executor.c and tests functions written in executor.c
3  */
4 #include <dlfcn.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <ffi.h>
8 
9 int main(int argc, char* argv) {
10 
11  void *lib_handle;
12  double (*pow)(double, double);
13  const char *dlsym_error;
14 
15  char *library_file = "/usr/lib/libm.dylib";
16  char *routine_name = "pow";
17  void (*routine_handle);
18 
19  // load the library libm
20  lib_handle = dlopen(library_file, RTLD_LAZY);
21 
22  // check we could open the library
23  if(!lib_handle) {
24  printf("Cannot open library: %s\n", dlerror());
25  return 1;
26  } else {
27  printf("Library opened: %s\n", library_file);
28  }
29 
30  //reset errors
31  dlerror();
32 
33  routine_handle = dlsym(lib_handle, routine_name);
34 
35  dlsym_error = dlerror();
36 
37  if(dlsym_error) {
38  printf("Cannot load symbol: 'pow': %s\n", dlsym_error);
39  dlclose(lib_handle);
40  return 1;
41  } else {
42  printf("Symbol loaded: %s\n", routine_name);
43  }
44 
45 
46  //printf("foo: %.2f\n", (double) routine_handle(4.0, 3.0));
47  {
48  ffi_cif cif;
49  ffi_type **args;
50  int n_args;
51  void **values;
52  double *rc;
53  int i;
54  double a, b;
55 
56  args = malloc(n_args*sizeof(ffi_type*));
57  values = malloc(n_args*sizeof(void*));
58  rc = malloc(sizeof(double));
59 
60  if(!args || !values || !rc) {
61  printf("Could not allocate memory for ffi\n");
62  return 1;
63  } else {
64  printf("ffi memory allocated\n");
65  }
66 
67  for(i=0; i<n_args; i++) {
68  args[i] = &ffi_type_double;
69 
70  }
71 
72  values[0] = &a;
73  values[1] = &b;
74 
75  if(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, n_args, &ffi_type_double, args) == FFI_OK) {
76 
77  ffi_call(&cif, routine_name, rc, values);
78 
79  printf("%d\n", (double)*rc);
80  }
81 
82 
83  for(i=0;i<n_args;i++) {
84  free(values[i]);
85  }
86  }
87  dlclose(lib_handle);
88  return 0;
89 }
90 
91