Hello Xojo and C Developers,
I’m facing a challenging issue where my application crashes after invoking an asynchronous C function from Xojo. The C function is expected to perform an operation in a new thread and then call back to update the Xojo UI after a few seconds. However, approximately three seconds after clicking the button that triggers the operation, the entire program crashes.
Here’s a snippet of the C code handling the asynchronous operation:
typedef void (*SimpleCallback)(void);
void *thread_func(void *arg) {
SimpleCallback callback = (SimpleCallback)arg;
sleep(3); // Simulate some operation
callback();
return NULL;
}
int start_async_operation(SimpleCallback callback) {
pthread_t thread;
int result = pthread_create(&thread, NULL, thread_func, (void *)callback);
if (result != 0) {
return -1;
}
pthread_detach(thread);
return 0;
}
And this is how I’m calling it from Xojo:
Declare Function start_async_operation Lib "Trxel.dll" (callback As Ptr) As Integer
Dim myCallbackDelegate As Ptr = AddressOf MyCallback
Dim result As Integer = start_async_operation(myCallbackDelegate)
Upon button press, start_async_operation
is called with a delegate to MyCallback
method. The program crashes without any exception or error message after a delay of about three seconds, which corresponds to the sleep duration in the C thread function.
Attached is the screenshot of my Xojo project where the DLL is being invoked.
I’ve attached a screenshot of my Xojo setup for reference.
I suspect the issue may be related to thread safety or improper synchronization when calling back into the Xojo UI thread from C. Has anyone encountered a similar issue, or does anyone have insights on ensuring the callback updates the UI safely without causing a crash? Any suggestions or advice would be greatly appreciated.
Please note that I am a student on campus and currently cannot afford paid subscription plugins. Hope to find a way to solve this problem without using any paid plugins
Thank you for your time and help!