В этом примере показано, как сгенерировать автономную библиотеку C из кода MATLAB, который читает файл из диска с помощью функций fopen/fread/fclose.
readfile
Функцияreadfile.m
функционируйте берет имя файла (или путь), как введено и возвращает строку, содержащую содержимое файла.
type readfile
% y = readfile(filename) % Read file 'filename' and return a MATLAB string with the contents % of the file. function y = readfile(filename) %#codegen % Put class and size constraints on function input. assert(isa(filename, 'char')); assert(size(filename, 1) == 1); assert(size(filename, 2) <= 1024); % Call fopen(filename 'r'), but we need to convert the MATLAB % string into a C type string (which is the same string with the % NUL (\0) string terminator). f = fopen(filename, 'r'); % Call fseek(f, 0, SEEK_END) to set file position to the end of % the file. fseek(f, 0, 'eof'); % Call ftell(f) which will return the length of the file in bytes % (as current file position is at the end of the file). filelen = int32(ftell(f)); % Reset current file position fseek(f,0,'bof'); % Initialize a buffer maxBufferSize = int32(2^16); buffer = zeros(1, maxBufferSize,'uint8'); % Remaining is the number of bytes to read (from the file) remaining = filelen; % Index is the current position to read into the buffer index = int32(1); while remaining > 0 % Buffer overflow? if remaining + index > size(buffer,2) fprintf('Attempt to read file which is bigger than internal buffer.\n'); fprintf('Current buffer size is %d bytes and file size is %d bytes.\n', maxBufferSize, filelen); break end % Read as much as possible from the file into internal buffer [dataRead, nread] = fread(f,remaining, 'char'); buffer(index:index+nread-1) = dataRead; n = int32(nread); if n == 0 % Nothing more to read break; end % Did something went wrong when reading? if n < 0 fprintf('Could not read from file: %d.\n', n); break; end % Update state variables remaining = remaining - n; index = index + n; end % Close file fclose(f); y = char(buffer(1:index));
Сгенерируйте MEX-функцию с помощью codegen
команда.
codegen readfile
Прежде, чем сгенерировать код С, необходимо сначала протестировать MEX-функцию в MATLAB, чтобы гарантировать, что это функционально эквивалентно оригинальному коду MATLAB и что никакие ошибки времени выполнения не происходят. По умолчанию, codegen
генерирует MEX-функцию под названием readfile_mex
в текущей папке. Это позволяет вам тестировать код MATLAB и MEX-функцию и сравнивать результаты.
Вызовите сгенерированную MEX-функцию и отобразите размер возвращаемой строки и ее первых 100 символов.
y = readfile_mex('readfile.m');
size(y)
ans = 1×2
1 1857
y(1:100)
ans = '% y = readfile(filename) % Read file 'filename' and return a MATLAB string with the contents % of th'
codegen -config:lib readfile
Используя codegen
с заданным -config cfg
опция производит автономную библиотеку C.
По умолчанию код, сгенерированный для библиотеки, находится в папке codegen/lib/readfile/
.
Файлы:
dir codegen/lib/readfile/
. ftell.c readfile_emxutil.o .. ftell.h readfile_initialize.c buildInfo.mat ftell.o readfile_initialize.h codeInfo.mat interface readfile_initialize.o codedescriptor.dmr readfile.a readfile_ref.rsp compileInfo.mat readfile.c readfile_rtw.mk examples readfile.h readfile_rtwutil.c fileManager.c readfile.o readfile_rtwutil.h fileManager.h readfile_data.c readfile_rtwutil.o fileManager.o readfile_data.h readfile_terminate.c fread.c readfile_data.o readfile_terminate.h fread.h readfile_emxAPI.c readfile_terminate.o fread.o readfile_emxAPI.h readfile_types.h fseek.c readfile_emxAPI.o rtw_proj.tmw fseek.h readfile_emxutil.c rtwtypes.h fseek.o readfile_emxutil.h
readfile.c
Функцияtype codegen/lib/readfile/readfile.c
/* * File: readfile.c * * MATLAB Coder version : 5.0 * C/C++ source code generated on : 29-Jan-2020 14:22:27 */ /* Include Files */ #include "readfile.h" #include "fileManager.h" #include "fread.h" #include "fseek.h" #include "ftell.h" #include "readfile_data.h" #include "readfile_emxutil.h" #include "readfile_initialize.h" #include "readfile_rtwutil.h" #include <stdio.h> #include <string.h> /* Function Definitions */ /* * Put class and size constraints on function input. * Arguments : const char filename_data[] * const int filename_size[2] * emxArray_char_T *y * Return Type : void */ void readfile(const char filename_data[], const int filename_size[2], emxArray_char_T *y) { signed char fileid; double d; int i; unsigned char buffer[65536]; int remaining; int b_index; emxArray_real_T *dataRead; boolean_T exitg1; int qY; double nread; int i1; int i2; unsigned char u; if (!isInitialized_readfile) { readfile_initialize(); } /* y = readfile(filename) */ /* Read file 'filename' and return a MATLAB string with the contents */ /* of the file. */ /* Call fopen(filename 'r'), but we need to convert the MATLAB */ /* string into a C type string (which is the same string with the */ /* NUL (\0) string terminator). */ fileid = cfopen(filename_data, filename_size, "rb"); /* Call fseek(f, 0, SEEK_END) to set file position to the end of */ /* the file. */ b_fseek(fileid); /* Call ftell(f) which will return the length of the file in bytes */ /* (as current file position is at the end of the file). */ d = rt_roundd_snf(b_ftell(fileid)); if (d < 2.147483648E+9) { if (d >= -2.147483648E+9) { i = (int)d; } else { i = MIN_int32_T; } } else if (d >= 2.147483648E+9) { i = MAX_int32_T; } else { i = 0; } /* Reset current file position */ c_fseek(fileid); /* Initialize a buffer */ memset(&buffer[0], 0, 65536U * sizeof(unsigned char)); /* Remaining is the number of bytes to read (from the file) */ remaining = i; /* Index is the current position to read into the buffer */ b_index = 1; emxInit_real_T(&dataRead, 1); exitg1 = false; while ((!exitg1) && (remaining > 0)) { /* Buffer overflow? */ if (b_index > MAX_int32_T - remaining) { qY = MAX_int32_T; } else { qY = remaining + b_index; } if (qY > 65536) { printf("Attempt to read file which is bigger than internal buffer.\n"); fflush(stdout); printf("Current buffer size is %d bytes and file size is %d bytes.\n", 65536, i); fflush(stdout); exitg1 = true; } else { /* Read as much as possible from the file into internal buffer */ b_fread(fileid, remaining, dataRead, &nread); d = rt_roundd_snf((double)b_index + nread); if (d < 2.147483648E+9) { if (d >= -2.147483648E+9) { qY = (int)d; } else { qY = MIN_int32_T; } } else if (d >= 2.147483648E+9) { qY = MAX_int32_T; } else { qY = 0; } if (qY < -2147483647) { qY = MIN_int32_T; } else { qY--; } if (b_index > qY) { i1 = -1; qY = 0; } else { i1 = b_index - 2; } qY = (qY - i1) - 1; for (i2 = 0; i2 < qY; i2++) { d = rt_roundd_snf(dataRead->data[i2]); if (d < 256.0) { if (d >= 0.0) { u = (unsigned char)d; } else { u = 0U; } } else if (d >= 256.0) { u = MAX_uint8_T; } else { u = 0U; } buffer[(i1 + i2) + 1] = u; } d = rt_roundd_snf(nread); if (d < 2.147483648E+9) { if (d >= -2.147483648E+9) { qY = (int)d; } else { qY = MIN_int32_T; } } else if (d >= 2.147483648E+9) { qY = MAX_int32_T; } else { qY = 0; } if (qY == 0) { /* Nothing more to read */ exitg1 = true; } else { /* Did something went wrong when reading? */ if (qY < 0) { printf("Could not read from file: %d.\n", qY); fflush(stdout); exitg1 = true; } else { /* Update state variables */ remaining -= qY; if ((b_index < 0) && (qY < MIN_int32_T - b_index)) { b_index = MIN_int32_T; } else if ((b_index > 0) && (qY > MAX_int32_T - b_index)) { b_index = MAX_int32_T; } else { b_index += qY; } } } } } emxFree_real_T(&dataRead); /* Close file */ cfclose(fileid); i = y->size[0] * y->size[1]; y->size[0] = 1; y->size[1] = b_index; emxEnsureCapacity_char_T(y, i); for (i = 0; i < b_index; i++) { y->data[i] = (signed char)buffer[i]; } } /* * File trailer for readfile.c * * [EOF] */