Skip to content

Instantly share code, notes, and snippets.

@pao
Last active October 5, 2015 16:07
Show Gist options
  • Save pao/2833165 to your computer and use it in GitHub Desktop.
Save pao/2833165 to your computer and use it in GitHub Desktop.
Using strpack.jl as an FFI

Note

strpack.jl is deprecated. Use the StrPack package or Julia's native C struct interop instead, depending on your needs.

Using strpack.jl as an FFI

This gist demonstrates calling C code which expects a structure pointer by writing and reading a buffer using the functions provided by strpack.jl. This takes advantage of the new align_native alignment strategy, which queries libLLVM for the platform-preferred alignment of the standard bits types.

Build the shared library

gcc -Wall -fPIC -c *.c
cc -shared -Wl,-soname,libtest.so -o libtest.so *.o

Show the result of calling the shared library from Julia

julia> load("struct_test.jl")

julia> foo
Foo(1,4.0,0x07)

julia> foo2
Foo(2,11.0,0x06)
#include <stdint.h>
typedef struct {
int32_t bar;
double baz;
uint8_t bat;
} foo;
void foobar(foo* x) {
x->bar++;
x->baz = x->baz + (double)(x->bat);
x->bat--;
}
load("strpack.jl")
type Foo
bar::Int32
baz::Float64
bat::Uint8
end
const libtest = dlopen("libtest.so")
foo = Foo(int32(1), 4.0, uint8(7))
foobuf = pack(foo, align_native)
ccall(dlsym(libtest, :foobar), Void, (Ptr{Uint8},), foobuf.data)
seek(foobuf, 0)
foo2 = unpack(foobuf, Foo, align_native)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment