I am trying to interface a C library (beaglebone PRU driver prussdrv.c) with Python. The particular function I want to access returns a mmap pointer as illustrated below:
int __prussdrv_memmap_init(void) {
prussdrv.pru0_dataram_base = mmap(0, prussdrv.pruss_map_size, PROT_READ | PROT_WRITE,
MAP_SHARED, prussdrv.mmap_fd, PRUSS_UIO_MAP_OFFSET_PRUSS);
...
int prussdrv_map_prumem(unsigned int pru_ram_id, void **address) {
switch (pru_ram_id) {
case PRUSS0_PRU0_DATARAM:
*address = prussdrv.pru0_dataram_base;
break;
prussdrv_map_prumem (DATARAM[PRU_NUM], &pruDataMem);
pruDataMem_byte = (unsigned char*) pruDataMem;
I would like to encapsulate either pruDataMem or pruDataMem_byte and pass it to Python as a mmap object. Is there a straightforward way to do this? I’ve looked at capsule and ctypes but they do not appear to do what I am looking for?
I don’t think there’s any way to create a Python
mmapobject out of a native mapping like this. The protocol isn’t published, and neither is the internal format.But of course the source is available. So, as long as your mapping meets all the same criteria as one created by
new_mmap_object, you could manually construct anmmap_objectwrapping the information, and pass it back. (You can’t actually access themmap_objecttype, because it’s not in any header file. But if you create an equivalent type, or just copy-and-paste the code, you’ll be passing it around as aPyObject *, and as long as its type field points to the right type, it’ll work.)However, I’m not sure you need to do this. Do you really need an
mmap, or just any buffer that you can treat as a string/list/iterator? Because the latter is a lot easier. For that, you can just create an old-style buffer or new-style buffer class—or, if you only need 2.7+, use the concretememoryviewtype. Conceptually, it seems to make sense that you’re returning a view of the mapped memory, rather than the mapping itself, but I can imagine some use cases where this might be inappropriate.Finally, you can always create a new class that exposes whatever interface you want around your mapping, and make it as much (or as little) like
mmapas you want.