Date: 2022-03-04T17:36:57+00:00

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: PetscErrorCode PetscBinaryRead(int,void *p,int,int*,PetscDataType);

     13: #define PETSC_MEX_ERROR(a) {fprintf(stdout,"sread: %s \n",a); return;}
     14: /*-----------------------------------------------------------------*/
     15: /*                                                                 */
     16: /*-----------------------------------------------------------------*/
     17: PETSC_EXTERN void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
     18: {
     19:   int            fd,cnt,dt;

     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:     PetscBinaryRead(fd,mxGetPr(plhs[0]),cnt,NULL,(PetscDataType)dt);if (ierr) PETSC_MEX_ERROR("Unable to receive double items.");
     32:   } else if (dt == PETSC_INT) {
     33:     plhs[0] = mxCreateNumericMatrix(1,cnt,mxINT32_CLASS,mxREAL);
     34:     PetscBinaryRead(fd,mxGetPr(plhs[0]),cnt,NULL,(PetscDataType)dt);if (ierr) PETSC_MEX_ERROR("Unable to receive int items.");
     35:   } else if (dt == PETSC_CHAR) {
     36:     char *tmp = (char*) mxMalloc(cnt*sizeof(char));
     37:     PetscBinaryRead(fd,tmp,cnt,NULL,(PetscDataType)dt);if (ierr) PETSC_MEX_ERROR("Unable to receive char items.");
     38:     plhs[0] = mxCreateStringFromNChars(tmp,cnt);
     39:     mxFree(tmp);
     40:   } else PETSC_MEX_ERROR("Unknown datatype.");
     41:   return;
     42: }

     44: int main(int argc, char **argv)
     45: {
     46:   return 0;
     47: }