Actual source code: sread.c

      1: /*

      3:     This is the equivalent of MATLAB's fread() only on sockets instead of
      4:    binary files.
      5: */

      7: #include <petscsys.h>
      8: #include <../src/sys/classes/viewer/impls/socket/socket.h>
      9: #include <mex.h>

     11: #define PETSC_MEX_ERROR(a) \
     12:   { \
     13:     fprintf(stdout, "sread: %s \n", a); \
     14:     return; \
     15:   }

     17: PETSC_EXTERN void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
     18: {
     19:   int            fd, cnt, dt;
     20:   PetscErrorCode ierr;

     22:   /* check output parameters */
     23:   if (nlhs != 1) PETSC_MEX_ERROR("Receive requires one output argument.");
     24:   if (nrhs != 3) PETSC_MEX_ERROR("Receive requires three input arguments.");
     25:   fd  = (int)mxGetScalar(prhs[0]);
     26:   cnt = (int)mxGetScalar(prhs[1]);
     27:   dt  = (PetscDataType)mxGetScalar(prhs[2]);

     29:   if (dt == PETSC_DOUBLE) {
     30:     plhs[0] = mxCreateDoubleMatrix(1, cnt, mxREAL);
     31:     ierr    = PetscBinaryRead(fd, mxGetPr(plhs[0]), cnt, NULL, (PetscDataType)dt);
     32:     if (ierr) PETSC_MEX_ERROR("Unable to receive double items.");
     33:   } else if (dt == PETSC_INT) {
     34:     plhs[0] = mxCreateNumericMatrix(1, cnt, mxINT32_CLASS, mxREAL);
     35:     ierr    = PetscBinaryRead(fd, mxGetPr(plhs[0]), cnt, NULL, (PetscDataType)dt);
     36:     if (ierr) PETSC_MEX_ERROR("Unable to receive int items.");
     37:   } else if (dt == PETSC_CHAR) {
     38:     char *tmp = (char *)mxMalloc(cnt * sizeof(char));
     39:     ierr      = PetscBinaryRead(fd, tmp, cnt, NULL, (PetscDataType)dt);
     40:     if (ierr) PETSC_MEX_ERROR("Unable to receive char items.");
     41:     plhs[0] = mxCreateStringFromNChars(tmp, cnt);
     42:     mxFree(tmp);
     43:   } else PETSC_MEX_ERROR("Unknown datatype.");
     44:   return;
     45: }

     47: int main(int argc, char **argv)
     48: {
     49:   return 0;
     50: }