Skip to content

Instantly share code, notes, and snippets.

@eliotb
Created September 3, 2015 02:51
Show Gist options
  • Save eliotb/d41b8383434ba221126d to your computer and use it in GitHub Desktop.
Save eliotb/d41b8383434ba221126d to your computer and use it in GitHub Desktop.
Experiment with ctypes interface to string read/write from python string, bytearray, list or tuple
// Build library with : gcc -o ba.so -fPIC -shared ba.c
#include <string.h>
#include <stdio.h>
static unsigned char buf[100];
static size_t blen = 0;
int write(const char *pc, size_t len)
{
if (len > 100)
return 1;
memcpy(buf, pc, len);
blen = len;
// printf("blen %zd\n", blen);
return 0;
}
int read(char *pc, size_t *len, size_t buflen)
{
if (buflen < blen)
return 1;
memcpy(pc, buf, blen);
*len = blen;
return 0;
}
#!/usr/bin/env python
from __future__ import print_function
from ctypes import *
import os
import struct
absfile = os.path.abspath(__file__)
abspath = os.path.dirname(absfile)
libpath = abspath + '/ba.so'
lib = CDLL(libpath)
lib.read.argtypes = [c_void_p, POINTER(c_size_t), c_size_t]
lib.write.argtypes = [c_void_p, c_size_t]
def test(data):
# Maybe a better way to do this, but it works
# for raw string, bytearray, list, tuple
if not isinstance(data, (bytes, str)):
if not isinstance(data, bytearray):
data = bytearray(data)
data = bytes(data)
try:
lib.write(data, len(data))
print('Wrote', dl, 'datalen', len(data))
except Exception as e:
print('Failed wb', e)
rb = create_string_buffer(10)
rlen = c_size_t()
err = lib.read(rb, rlen, len(rb))
if not err:
rd = bytearray(rb.raw[:rlen.value])
print('Read', repr(rd), list(rd))
return rd
else:
print('Read error', err)
return None
l = [00, 41, 42, 43, 44, 54, 46]
print('\nTest list', repr(l))
test(l)
S = struct.Struct('>BBHI')
s = S.pack(*l[:4])
print('\nTest raw string', repr(s))
r = test(s)
print(S.unpack(r))
b = bytearray(l[:6])
print('\nTest bytearray', list(b))
test(b)
t = tuple(l[4:])
print('\nTest tuple', repr(t))
test(t)
s = 'string'
print('\nTest string', repr(s))
try:
test(s)
except Exception as e:
print(e)
print('Expect to fail on python 3')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment