Skip to content

Instantly share code, notes, and snippets.

@Nican
Last active December 1, 2023 05:42
Show Gist options
  • Save Nican/5198719 to your computer and use it in GitHub Desktop.
Save Nican/5198719 to your computer and use it in GitHub Desktop.
Python callback
############## main.c ##############
#include <stdint.h>
#include <stdio.h>
struct mes_t
{
uint32_t field1;
uint32_t field2;
void* data;
};
typedef int function_callback(struct mes_t* message );
function_callback* my_callback;
int function_one(function_callback fcb){
//Set to a global variable for later use
my_callback = fcb;
//Declare object in stack
struct mes_t mes;
mes.field1 = 132;
mes.field2 = 264;
mes.data = NULL;
//Pass pointer of object in stack, and print the return value
printf("Got from python: %d\n", my_callback( &mes ) );
}
############ main.py ################
import ctypes
testlib = ctypes.CDLL('./testlib.so')
#Declare the data structure
class mes_t(ctypes.Structure):
_fields_ = (
('field1', ctypes.c_uint32),
('field2', ctypes.c_uint32),
('data', ctypes.c_void_p))
#Declare the callback type, since that is not stored in the library
callback_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(mes_t) )
def the_callback(mes_p):
#dereference the pointer
my_mes = mes_p[0]
print "I got a mes_t object! mes.field1=%r, mes.field2=%r, mes.data=%r" \
% (my_mes.field1, my_mes.field2, my_mes.data)
#Return some random value
return 999
#Let the library know about the callback function by calling "function_one"
result = testlib.function_one(callback_type(the_callback) )
#########################
gcc -shared -o testlib.so -fPIC main.c
python main.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment