Hi all, I'm writing a module in C, which needs to access the filesystem. I'm using a STM32.
I was looking through the source, and this file seems to expose the file read/write commands: https://github.com/micropython/micropyt ... pybstdio.c
I note that there are no open/close/list commands, so if someone could point me in the right direction that would be greatly appreciated.
Thanks, Matt
Accessing the filesystem from a C module
Re: Accessing the filesystem from a C module
The function to open a file is just called "open". Currently this is implemented on a per-port basis.
It's currently exposed to python and doesn't have a C friiendly API, but you can call it from C by doing something like the following:
The functions in pybstdio.c are for reading stdin/stdout - i.e. input and output used by the REPL, which is typically UART or USB based.
You can read from that file object by using mp_stream_obj. I don't see any convenient C API which is exposed, so you could also just lookup the read function by doing something like: and then setup args and call the read_fn using mp_call_function_xxx (replace xxx by the number of arguments). I've done readinto using the following:
It's currently exposed to python and doesn't have a C friiendly API, but you can call it from C by doing something like the following:
Code: Select all
const char *filename = "/flash/somefile.txt";
const char *mode = "rb";
mp_obj_t filename_obj = mp_obj_new_str(filename, strlen(filename), false);
mp_obj_t mode_obj = mp_obj_new_str(mode, strlen(mode), true);
mp_obj_t args[2] = { filename_obj, mode_obj };
mp_obj_t file = mp_builtin_open(2, args, (mp_map_t *)&mp_const_empty_map);
You can read from that file object by using mp_stream_obj. I don't see any convenient C API which is exposed, so you could also just lookup the read function by doing something like:
Code: Select all
read_fn = mp_load_attr(file, MP_QSTR_read);
Code: Select all
readinto_fn = mp_load_attr(file, MP_QSTR_readinto);
mp_obj_t bytearray = mp_obj_new_bytearray_by_ref(num_bytes, buf);
mp_obj_t bytes_read = mp_call_function_1(readinto_fn, bytearray);
Re: Accessing the filesystem from a C module
Thanks, I tried to call the exposed python calls, but I wasnt having much luck. For example, it wasnt obvious how you give a file handle to read, and I couldnt find the difference between the various read functions, or where the relevant code is to look through.
In the end, it turned out the library I'm wrapping for micropython can directly call the fatfs functions, and so it can interact with the micropython filesystem without modification. This system is still being tested, but it appears to be working fine.
Matt
In the end, it turned out the library I'm wrapping for micropython can directly call the fatfs functions, and so it can interact with the micropython filesystem without modification. This system is still being tested, but it appears to be working fine.
Matt