coffi/test/c/ffi_test.c

124 lines
2.1 KiB
C
Raw Normal View History

2021-09-22 18:39:02 +00:00
#include <stdio.h>
2024-10-04 15:43:01 +00:00
#include <stdlib.h>
2021-09-22 18:39:02 +00:00
2024-10-15 21:27:53 +00:00
const int c = 42;
const char *s = "Test string";
2024-10-15 21:27:53 +00:00
int add_numbers(int a, int b) {
return a + b;
}
2021-09-22 18:39:02 +00:00
typedef struct point {
float x;
float y;
} Point;
Point add_points(Point a, Point b) {
Point res = {};
res.x = a.x + b.x;
res.y = a.y + b.y;
return res;
}
typedef char *CString;
typedef CString (*StringFactory)(void);
CString upcall_test(StringFactory fun) {
2021-09-22 18:39:02 +00:00
return fun();
}
2024-06-17 17:57:15 +00:00
int upcall_test2(int (*f)(void)) {
return f();
}
char *mut_str = NULL;
2022-11-29 19:43:06 +00:00
int counter = 0;
2021-09-22 18:39:02 +00:00
static char* responses[] = { "Hello, world!", "Goodbye friend.", "co'oi prenu" };
2024-06-17 17:57:15 +00:00
char* upcall_test_int_fn_string_ret(int (*f)(void)) {
return responses[f()];
}
2021-09-22 18:39:02 +00:00
CString get_string1(void) {
2024-07-24 23:27:17 +00:00
return responses[counter++ % 3];
2021-09-22 18:39:02 +00:00
}
CString get_string2(void) {
2024-07-24 23:27:17 +00:00
return "Alternate string";
2021-09-22 18:39:02 +00:00
}
StringFactory get_downcall(int whichString) {
2024-07-24 23:27:17 +00:00
switch (whichString % 2) {
case 0:
return get_string1;
case 1:
return get_string2;
default:
return 0;
}
2021-09-22 18:39:02 +00:00
}
2022-01-10 20:37:56 +00:00
typedef struct alignment_test {
2024-07-24 23:27:17 +00:00
char a;
double x;
float y;
2022-01-10 20:37:56 +00:00
} AlignmentTest;
AlignmentTest get_struct() {
2024-07-24 23:27:17 +00:00
AlignmentTest ret = {};
ret.a = 'x';
ret.x = 3.14;
ret.y = 42.0;
2024-07-23 13:04:44 +00:00
2024-07-24 23:27:17 +00:00
return ret;
2024-07-23 13:04:44 +00:00
}
2022-01-10 20:37:56 +00:00
2024-07-23 13:04:44 +00:00
void test_call_with_trailing_string_arg(int a, int b, char* text) {
2024-07-24 23:27:17 +00:00
printf("call of `test_call_with_trailing_string_arg` with a=%i b=%i text='%s'",1,2,text);
printf("\r ");
return;
2022-01-10 20:37:56 +00:00
}
2024-07-23 13:04:44 +00:00
2024-10-04 15:43:01 +00:00
int freed = 0;
int get_variable_length_array(float **arr) {
freed = 0;
*arr = malloc(sizeof(float) * 7);
for (int i = 0; i < 7; ++i) {
(*arr)[i] = 1.5f * i;
}
return 7;
}
void free_variable_length_array(float *arr) {
freed = 1;
free(arr);
}
2024-10-28 21:47:38 +00:00
typedef struct complextype {
Point x;
char y;
int z[4];
char *w;
} ComplexType;
ComplexType complexTypeTest(ComplexType a) {
ComplexType ret = {};
ret.x = a.x;
ret.x.x++;
ret.x.y++;
ret.y = a.y-1;
ret.z[0] = a.z[0];
ret.z[1] = a.z[1];
ret.z[2] = a.z[2];
ret.z[3] = a.z[3];
ret.w = "hello from c";
return ret;
}