Actual source code: swrite.c

petsc-3.6.4 2016-04-12
Report Typos and Errors
  1: /*

  3:     This is the equivalent of MATLAB's fwrite() 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 PetscBinaryWrite(int,void *p,int,PetscDataType,PetscBool);

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

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

 30:   if (dt == PETSC_DOUBLE) {
 31:     PetscBinaryWrite(fd,mxGetPr(prhs[1]),cnt,(PetscDataType)dt,PETSC_FALSE);if (ierr) PETSC_MEX_ERROR("Unable to send double items.");
 32:   } else if (dt == PETSC_INT) {
 33:     int    *tmp = (int*) mxMalloc((cnt+5)*sizeof(int));
 34:     double *t   = mxGetPr(prhs[1]);
 35:     for (i=0; i<cnt; i++) tmp[i] = (int)t[i];
 36:     PetscBinaryWrite(fd,tmp,cnt,(PetscDataType)dt,PETSC_FALSE);if (ierr) PETSC_MEX_ERROR("Unable to send int items.");
 37:     mxFree(tmp);
 38:   } else if (dt == PETSC_CHAR) {
 39:     char *tmp = (char*) mxMalloc((cnt+5)*sizeof(char));
 40:     mxGetNChars(prhs[1],tmp,cnt+1);
 41:     PetscBinaryWrite(fd,tmp,cnt,(PetscDataType)dt,PETSC_FALSE);if (ierr) PETSC_MEX_ERROR("Unable to send char items.");
 42:     mxFree(tmp);
 43:   } else PETSC_MEX_ERROR("Unknown datatype.");
 44:   return;
 45: }