From 69e1a7ad9d2e459028e2078e9b4f6893ccca8989 Mon Sep 17 00:00:00 2001 From: Yohai Meiron Date: Tue, 4 Nov 2025 23:09:06 -0500 Subject: [PATCH] Added C interface --- Makefile | 8 +++++++- example.c | 26 ++++++++++++++++++++++++++ gravity.cpp | 30 ++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 example.c create mode 100644 gravity.cpp diff --git a/Makefile b/Makefile index 0886a1b..fbe3ae1 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,11 @@ +example: gravity.o + $(CC) -O3 example.c -o example gravity.o ../grapite/libgrapite.a -lcuda -lcudart -lstdc++ -lm + +gravity.o: + $(CXX) -O3 --std=c++23 gravity.cpp -c + main: $(CXX) -O3 main.cpp ../grapite/libgrapite.a -lcuda -lcudart -o $@ clean: - $(RM) main \ No newline at end of file + $(RM) main *.o \ No newline at end of file diff --git a/example.c b/example.c new file mode 100644 index 0000000..1fd8d0a --- /dev/null +++ b/example.c @@ -0,0 +1,26 @@ +#include + +void etics_external_init(const int n_total); +void etics_external_grav(const double* const A, const int n_act, double x_act[][3], double pot_act[], double a_act[][3]); + +int main() +{ + const int n_total = 1024; + etics_external_init(n_total); + + srand(19640916); + + double x_act[n_total][3], pot_act[n_total], a_act[n_total][3]; + for (int i = 0; i < n_total; i++) { + x_act[i][0] = rand(); + x_act[i][1] = rand(); + x_act[i][2] = rand(); + } + + double A[2048]; + for (int i = 0; i < 2048; i++) { + A[i] = rand(); + } + + etics_external_grav(A, n_total, x_act, pot_act, a_act); +} \ No newline at end of file diff --git a/gravity.cpp b/gravity.cpp new file mode 100644 index 0000000..925c9c9 --- /dev/null +++ b/gravity.cpp @@ -0,0 +1,30 @@ +#include +#include "../grapite/etics_interface.h" +#include "../grapite/particle_manager.h" + +static grapite::Active_particles* particles_i; +static grapite::Etics_interface* etics_interface; + +extern "C" +void etics_external_init(const int n_total) +{ + particles_i = new grapite::Active_particles{n_total}; + etics_interface = new grapite::Etics_interface{n_total}; +} + +extern "C" +void etics_external_grav(const double* const A, const int n_act, double x_act[][3], double pot_act[], double a_act[][3]) +{ + // Load coefficients + std::span A_complex{reinterpret_cast(A), 1024}; + std::copy(begin(A_complex), end(A_complex), etics_interface->A_h); + etics_interface->GetGpuLock(); + etics_interface->SendCoeffsToGPU(); + etics_interface->ReleaseGpuLock(); + + // Calculate potentials and forces + particles_i->ni_core = 0; + particles_i->ni_total = n_act; + particles_i->flush_memory(); + etics_interface->calculate_gravity(particles_i, grapite::Selector::halo, 0, pot_act, reinterpret_cast(a_act)); +} \ No newline at end of file