JNIEXPORT jint JNICALL Java_com_fazecast_jSerialComm_SerialPort_writeBytes()

in src/main/c/Posix/SerialPort_Posix.c [1052:1085]


JNIEXPORT jint JNICALL Java_com_fazecast_jSerialComm_SerialPort_writeBytes(JNIEnv *env, jobject obj, jlong serialPortPointer, jbyteArray buffer, jint bytesToWrite, jint offset, jint timeoutMode)
{
	// Ensure that a positive number of bytes was passed in to write
	serialPort *port = (serialPort*)(intptr_t)serialPortPointer;
	if ((bytesToWrite < 0) || (offset < 0))
		return -1;

	// Fetch a pointer to the underlying data buffer
	jsize bufferLength = (*env)->GetArrayLength(env, buffer);
	if ((bytesToWrite + offset) > bufferLength)
		bytesToWrite = bufferLength - offset;
	int writeBlockingMode = (timeoutMode & com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_BLOCKING);
	jbyte *writeBuffer = (*env)->GetByteArrayElements(env, buffer, NULL);
	if (checkJniError(env, __LINE__ - 1) || !writeBuffer)
		return -1;

	// Write to the port
	int numBytesWritten;
	do {
		errno = 0;
		port->errorLineNumber = __LINE__ + 1;
		numBytesWritten = write(port->handle, writeBuffer + offset, bytesToWrite);
		port->errorNumber = errno;
	} while ((numBytesWritten < 0) && ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK)));

	// Wait until all bytes were written in write-blocking mode
	if ((writeBlockingMode > 0) && (numBytesWritten > 0))
		tcdrain(port->handle);

	// Return the number of bytes written if successful
	(*env)->ReleaseByteArrayElements(env, buffer, writeBuffer, JNI_ABORT);
	checkJniError(env, __LINE__ - 1);
	return numBytesWritten;
}