示例工程 ch10-ffi
ch10-ffi/native/c/add.c
#include "add.h"
#include <stdlib.h>
#include <string.h>
int32_t add_i32(int32_t a, int32_t b) {
/* 与 Dart/Go 一致:定长发补码回绕(C 的有符号溢出是 UB,这里用无符号加法明确语义) */
return (int32_t)((uint32_t)a + (uint32_t)b);
}
double mul_f64(double a, double b) {
return a * b;
}
char *concat_strings(const char *a, const char *b) {
if (a == NULL || b == NULL) {
return NULL;
}
size_t la = strlen(a);
size_t lb = strlen(b);
char *out = (char *)malloc(la + lb + 1);
if (out == NULL) {
return NULL;
}
memcpy(out, a, la);
memcpy(out + la, b, lb);
out[la + lb] = '\0';
return out;
}
void free_string(char *s) {
free(s);
}
int32_t apply_cb(int32_t (*cb)(int32_t), int32_t x) {
if (cb == NULL) {
return -1;
}
return cb(x);
}