Skip to content

Instantly share code, notes, and snippets.

@soasme
Created July 18, 2018 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soasme/1ddbf4de79e341cbf2e0cf7357a166f7 to your computer and use it in GitHub Desktop.
Save soasme/1ddbf4de79e341cbf2e0cf7357a166f7 to your computer and use it in GitHub Desktop.
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
void (*f)(void);
void fatal(const char * info) {
printf("error: %s", info);
exit(1);
}
int main(int argc, char** argv) {
void* lib = dlopen("libmymodule.so", RTLD_LAZY);
if (lib == NULL)
fatal(dlerror());
f = (void (*)(void)) dlsym(lib, "get_point_distance");
printf("address: %p", f);
return 0;
}
ffi = require('ffi')
ffi.cdef[[
typedef struct point point_t;
struct point {
double x;
double y;
};
]]
local points = ffi.new("point_t[?]", n)
points[1].x = 1.0
points[2].y = 3.0
local ffi = require("ffi")
ffi.cdef[[
int printf(const char *fmt, ...);
]]
ffi.C.printf("Hello %s!", "world")
step0:
gcc -shared -o libmymodule.so -fPIC mymodule.c
#include <math.h>
#include "mymodule.h"
double get_point_distance(const point_t* p1, const point_t* p2) {
return sqrt((p2->x - p1->x) * (p2->x - p1->x) + (p2->y - p1->x) * (p2->y - p1->x));
}
#ifndef MYMODULE_H
#define MYMODULE_H
typedef struct point point_t;
struct point {
double x;
double y;
};
double get_point_distance(const point_t* p1, const point_t* p2);
#endif
ffi = FFI()
ffi.cdef("""
typedef struct point point_t;
struct point {
double x;
double y;
};
""")
points = ffi.new("point_t[]", 2)
points[0].x = 1.0
points[1].y = 3.0
from cffi import FFI
ffi = FFI()
ffi.cdef("""
int printf(const char *format, ...); // copy-pasted from the man page
""")
C = ffi.dlopen(None) # loads the entire C namespace
arg = ffi.new("char[]", "world") # equivalent to C code: char arg[] = "world";
C.printf("hi there, %s.\n", arg) # call printf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment