lang/python/ CTypesModule
Trivial Example
The c
#include <stdio.h>
#include <stdlib.h>
// compile with gcc -o a.so a.c
typedef struct {
int x;
} X;
X* create() {
X *x = (X*)malloc(sizeof(X));
x->x = 42;
return x;
}
int set(X* x, int y) {
x->x = y;
}
int get(X* x) {
return x->x;
}
void destroy(X* x) {
free(x);
}
The pyton
import ctypes
dll = ctypes.cdll.LoadLibrary("./a.so")
print(dll)
class X:
def __init__(self):
self.a = dll.create() # void* pointers are just integers in Python
def destroy(self):
dll.destroy(self.a)
def set(self,x): # we should be putting on type annotations in real code
x = int(x)
dll.set(self.a,x)
def get(self):
return dll.get(self.a)
x = X()
print(x.get())