Skip to content

Commit

Permalink
updated Python protokit.Pipe to support sending string, bytes, and by…
Browse files Browse the repository at this point in the history
…tearrays
  • Loading branch information
bebopagogo committed Mar 30, 2024
1 parent 05d685e commit ea55521
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 11 deletions.
19 changes: 16 additions & 3 deletions examples/protoPipeSend.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,20 @@
pipe = protokit.Pipe("MESSAGE")
pipe.Connect(sys.argv[1])

message = ' '.join(sys.argv[2:])
pipe.Send(message)
text = ' '.join(sys.argv[2:])

print("Sent message '%s'" % message)
# This sends the message as a string
msg = text

# Uncomment these two lines to send as bytearray
#msg = bytearray()
#msg.extend(map(ord, text))

# Uncomment this one to send as bytes (example/test)
#msg = text.encode('ascii')

x = 12

pipe.Send(x)

print("Sent message '%s'" % text)
67 changes: 59 additions & 8 deletions src/python/protopipe.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -131,16 +131,67 @@ extern "C" {
Py_RETURN_NONE;
}

static PyObject* Pipe_Send(Pipe *self, PyObject *args) {
const char *buffer;
Py_ssize_t size;

if (!PyArg_ParseTuple(args, "s#", &buffer, &size))
static PyObject* Pipe_Send(Pipe *self, PyObject *args)
{
const char* buffer;
unsigned int size_u;
PyObject* obj;
if (!PyArg_ParseTuple(args, "O", &obj))
{
PyErr_SetString(ProtoError, "Invalid argument.");
return NULL;
unsigned int size_u = size;

}
if (PyObject_TypeCheck(obj, &PyUnicode_Type))
{
//PySys_WriteStdout("sending string ...\n");
int size;
if (!PyArg_ParseTuple(args, "s#", &buffer, &size))
{
PyErr_SetString(ProtoError, "Invalid string.");
return NULL;
}
size_u = size;
}
else if (PyObject_TypeCheck(obj, &PyBytes_Type))
{
//PySys_WriteStdout("sending bytes ...\n");
Py_ssize_t size = PyBytes_Size(obj);
if (0 == size)
{
// Nothing to send
return NULL;
}
buffer = PyBytes_AsString(obj);
if (NULL == buffer)
{
// Nothing to send
return NULL;
}
size_u = size;
}
else if (PyObject_TypeCheck(obj, &PyByteArray_Type))
{
//PySys_WriteStdout("sending bytearray ...\n");
Py_ssize_t size = PyByteArray_Size(obj);
if (0 == size)
{
// Nothing to send
return NULL;
}
buffer = PyByteArray_AsString(obj);
if (NULL == buffer)
{
// Nothing to send
return NULL;
}
size_u = size;
}
else
{
PyErr_SetString(ProtoError, "Invalid argument type (must be str, bytes, or bytearray).");
return NULL;
}
//PySys_WriteStdout("sending message size %u\n", size_u);

if (!self->thisptr->Send(buffer, size_u)) {
PyErr_SetString(ProtoError, "Could not send buffer.");
return NULL;
Expand Down

0 comments on commit ea55521

Please sign in to comment.