Actual source code: swrite.c

  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, const void *p, int, PetscDataType);

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

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

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

 50: int main(int argc, char **argv)
 51: {
 52:   return 0;
 53: }