xref: /petsc/src/sys/classes/viewer/impls/socket/mex-scripts/sread.c (revision 4ee01570adce53535717956d9962247794ff2c83)
1b75c6efcSBarry Smith /*
2b75c6efcSBarry Smith 
3b75c6efcSBarry Smith     This is the equivalent of MATLAB's fread() only on sockets instead of
4b75c6efcSBarry Smith    binary files.
5b75c6efcSBarry Smith */
6b75c6efcSBarry Smith 
7b75c6efcSBarry Smith #include <petscsys.h>
8b75c6efcSBarry Smith #include <../src/sys/classes/viewer/impls/socket/socket.h>
9b75c6efcSBarry Smith #include <mex.h>
10b75c6efcSBarry Smith 
11b75c6efcSBarry Smith PetscErrorCode PetscBinaryRead(int, void *p, int, int *, PetscDataType);
12b75c6efcSBarry Smith 
13b75c6efcSBarry Smith #define PETSC_MEX_ERROR(a) \
14b75c6efcSBarry Smith   { \
15b75c6efcSBarry Smith     fprintf(stdout, "sread: %s \n", a); \
16b75c6efcSBarry Smith     return; \
17b75c6efcSBarry Smith   }
18*4ee01570SBarry Smith 
19b75c6efcSBarry Smith PETSC_EXTERN void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
20b75c6efcSBarry Smith {
21b75c6efcSBarry Smith   int            fd, cnt, dt;
22b75c6efcSBarry Smith   PetscErrorCode ierr;
23b75c6efcSBarry Smith 
24b75c6efcSBarry Smith   /* check output parameters */
25b75c6efcSBarry Smith   if (nlhs != 1) PETSC_MEX_ERROR("Receive requires one output argument.");
26b75c6efcSBarry Smith   if (nrhs != 3) PETSC_MEX_ERROR("Receive requires three input arguments.");
27b75c6efcSBarry Smith   fd  = (int)mxGetScalar(prhs[0]);
28b75c6efcSBarry Smith   cnt = (int)mxGetScalar(prhs[1]);
29b75c6efcSBarry Smith   dt  = (PetscDataType)mxGetScalar(prhs[2]);
30b75c6efcSBarry Smith 
31b75c6efcSBarry Smith   if (dt == PETSC_DOUBLE) {
32b75c6efcSBarry Smith     plhs[0] = mxCreateDoubleMatrix(1, cnt, mxREAL);
33b75c6efcSBarry Smith     ierr    = PetscBinaryRead(fd, mxGetPr(plhs[0]), cnt, NULL, (PetscDataType)dt);
34b75c6efcSBarry Smith     if (ierr) PETSC_MEX_ERROR("Unable to receive double items.");
35b75c6efcSBarry Smith   } else if (dt == PETSC_INT) {
36b75c6efcSBarry Smith     plhs[0] = mxCreateNumericMatrix(1, cnt, mxINT32_CLASS, mxREAL);
37b75c6efcSBarry Smith     ierr    = PetscBinaryRead(fd, mxGetPr(plhs[0]), cnt, NULL, (PetscDataType)dt);
38b75c6efcSBarry Smith     if (ierr) PETSC_MEX_ERROR("Unable to receive int items.");
39b75c6efcSBarry Smith   } else if (dt == PETSC_CHAR) {
40b75c6efcSBarry Smith     char *tmp = (char *)mxMalloc(cnt * sizeof(char));
41b75c6efcSBarry Smith     ierr      = PetscBinaryRead(fd, tmp, cnt, NULL, (PetscDataType)dt);
42b75c6efcSBarry Smith     if (ierr) PETSC_MEX_ERROR("Unable to receive char items.");
43b75c6efcSBarry Smith     plhs[0] = mxCreateStringFromNChars(tmp, cnt);
44b75c6efcSBarry Smith     mxFree(tmp);
45b75c6efcSBarry Smith   } else PETSC_MEX_ERROR("Unknown datatype.");
46b75c6efcSBarry Smith   return;
47b75c6efcSBarry Smith }
48b75c6efcSBarry Smith 
49b75c6efcSBarry Smith int main(int argc, char **argv)
50b75c6efcSBarry Smith {
51b75c6efcSBarry Smith   return 0;
52b75c6efcSBarry Smith }
53