Skip to content

Commit 80a0c54

Browse files
committed
Implementation files (in C) for libpkl as described in SPICE
1 parent b4a1171 commit 80a0c54

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

libpkl/src/main/c/libpkl.c

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include <stdlib.h>
2+
#include <stdio.h>
3+
#include <pthread.h>
4+
5+
#include <graal_isolate.h>
6+
#include <libpkl-macos-aarch64.h>
7+
8+
#include <libpkl.h>
9+
10+
#ifndef NULL
11+
#define NULL 0
12+
#endif
13+
14+
pthread_mutex_t graal_mutex;
15+
graal_isolatethread_t *isolatethread = NULL;
16+
17+
int pkl_init(PklMessageResponseHandler handler) {
18+
if (isolatethread != NULL) {
19+
perror("pkl_init: isolatethread is already initialised");
20+
return -1;
21+
}
22+
23+
if (pthread_mutex_init(&graal_mutex, NULL) != 0) {
24+
perror("pkl_init: couldn't initialise pthread_mutex");
25+
return -1;
26+
}
27+
28+
if (pthread_mutex_lock(&graal_mutex) != 0) {
29+
return -1;
30+
}
31+
32+
isolatethread = pkl_internal_init();
33+
pkl_internal_register_response_handler(isolatethread, handler);
34+
pkl_internal_server_start(isolatethread);
35+
pthread_mutex_unlock(&graal_mutex);
36+
37+
return 0;
38+
};
39+
40+
41+
int pkl_send_message(int length, char* message) {
42+
if (pthread_mutex_lock(&graal_mutex) != 0) {
43+
return -1;
44+
}
45+
46+
pkl_internal_send_message(isolatethread, length, message);
47+
pthread_mutex_unlock(&graal_mutex);
48+
49+
return 0;
50+
};
51+
52+
int pkl_close() {
53+
if (pthread_mutex_lock(&graal_mutex) != 0) {
54+
return -1;
55+
}
56+
57+
pkl_internal_server_stop(isolatethread);
58+
pkl_internal_close(isolatethread);
59+
60+
if (pthread_mutex_unlock(&graal_mutex) != 0) {
61+
return -1;
62+
}
63+
64+
if (pthread_mutex_destroy(&graal_mutex) != 0) {
65+
return -1;
66+
}
67+
68+
return 0;
69+
};

libpkl/src/main/c/libpkl.h

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @brief The Pkl Message Response Handler that a user should implement.
3+
*
4+
* The resulting messages from `pkl_send` will be sent to this
5+
* handler using a callback style.
6+
*/
7+
typedef void (*PklMessageResponseHandler)(int length, char* message);
8+
9+
/**
10+
* @brief Initialises and allocates a Pkl executor.
11+
*
12+
* @return -1 on failure.
13+
* @return 0 on success.
14+
*/
15+
int pkl_init(PklMessageResponseHandler handler);
16+
17+
/**
18+
* @brief Send a message to Pkl, providing the length and a pointer to the first byte.
19+
*
20+
* @return -1 on failure.
21+
* @return 0 on success.
22+
*/
23+
int pkl_send_message(int length, char* message);
24+
25+
/**
26+
* @brief Cleans up any resources that were created as part of the `pkl_init` process.
27+
*
28+
* @return -1 on failure.
29+
* @return 0 on success.
30+
*/
31+
int pkl_close();

0 commit comments

Comments
 (0)