Skip to content

Instantly share code, notes, and snippets.

@jgomezdans
Created December 3, 2009 14:57
Show Gist options
  • Save jgomezdans/248213 to your computer and use it in GitHub Desktop.
Save jgomezdans/248213 to your computer and use it in GitHub Desktop.
ctypes wrapper example
import ctypes
"""
The Coord struct in C-land
typedef struct
{
double lon,lat;
double area;
} Coord;
The Config struct in C-land
typedef struct
{
char *pftpar_filename;
char *soilpar_filename;
char *coord_filename;
char *soil_filename;
char *temp_filename;
char *prec_filename;
char *cloud_filename;
char *wet_filename;
char *co2_filename;
char *restart_filename;
char *write_restart_filename;
char **out_filename;
int ngridcell,startgrid,nspinup,lastyear,totalgridcell,firstyear;
int n_out;
int seed;
Coord resolution;
} Config;"""
class COORD ( ctypes.Structure ):
_fields = [ ("lon",ctypes.c_double),\
("lat", ctypes.c_double),\
("area", ctypes.c_double)]
coords = COORD()
class CONFIG( ctypes.Structure ):
_fields = [ ("pftpar_filename", ctypes.c_char_p),\
("soilpar_filename", ctypes.c_char_p),\
("coord_filename", ctypes.c_char_p),\
("soil_filename", ctypes.c_char_p),\
("temp_filename", ctypes.c_char_p),\
("prec_filename", ctypes.c_char_p),\
("cloud_filename", ctypes.c_char_p),\
("wet_filename", ctypes.c_char_p),\
("co2_filename", ctypes.c_char_p),\
("restart_filename", ctypes.c_char_p),\
("write_restart_filename", ctypes.c_char_p),\
("out_filename", ctypes.POINTER(ctypes.c_char_p)),\
("ngridcell", ctypes.c_int),\
("startgrid", ctypes.c_int),\
("nspinup", ctypes.c_int),\
("lastyear", ctypes.c_int),\
("totalgridcell", ctypes.c_int),\
("firstyear", ctypes.c_int),\
("n_out", ctypes.c_int),\
("seed", ctypes.c_int),\
("resolution", COORD ) ]
lpj = ctypes.CDLL("./liblpj.so.1")
fscanconfig = lpj['fscanconfig']
fscanconfig.argtypes = [ctypes.POINTER( CONFIG), ctypes.POINTER(ctypes.c_int),\
ctypes.POINTER(ctypes.c_char_p)]
fscanconfig.restype = ctypes.c_int
config = CONFIG()
argc = ctypes.c_int(4)
myargv = ctypes.c_char_p *4
argv = myargv("One","Two","Three","Four") # the 1st argv is the program name
Argv = ctypes.pointer ( argv )
urg = fscanconfig ( ctypes.byref(config), ctypes.byref(argc), ctypes.byref(Argv) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment