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