X11 Equivalent of gdk_pixbuf_add_alpha - gtk

In x11 I have obtained the binary blob by using XGetImage.
In GDK we have this function that adds alpha of 255 to the Pixbuf: https://developer.gnome.org/gdk-pixbuf/stable/gdk-pixbuf-Utilities.html#gdk-pixbuf-add-alpha
I was wondering if there is a convenient function like this in X11.
So I have a struct like this:
typedef struct _XImage {
int width, height; /* size of image */
int xoffset; /* number of pixels offset in X direction */
int format; /* XYBitmap, XYPixmap, ZPixmap */
char *data; /* pointer to image data */
int byte_order; /* data byte order, LSBFirst, MSBFirst */
int bitmap_unit; /* quant. of scanline 8, 16, 32 */
int bitmap_bit_order; /* LSBFirst, MSBFirst */
int bitmap_pad; /* 8, 16, 32 either XY or ZPixmap */
int depth; /* depth of image */
int bytes_per_line; /* accelerator to next scanline */
int bits_per_pixel; /* bits per pixel (ZPixmap) */
unsigned long red_mask; /* bits in z arrangement */
unsigned long green_mask;
unsigned long blue_mask;
XPointer obdata; /* hook for the object routines to hang on */
struct funcs { /* image manipulation routines */
struct _XImage *(*create_image)();
int (*destroy_image)();
unsigned long (*get_pixel)();
int (*put_pixel)();
struct _XImage *(*sub_image)();
int (*add_pixel)();
} f;
} XImage;
And in the ximage.data field I have RGB binary data. Im helping a friend and I need to make that RGBA binary data.
Thanks

Unfortually there is no such abstraction as in GDK.
You have to do it manually by iterating on the *char data member.

Related

PyArg_ParseTuple doesn't parse a string correctly

So I'm learning how to make Python modules in C and today I wanted to learn how to create a custom type.
I wrote a module with one class named "Car" which stores a name, year and maxGas.
Problem is, when I try to create an instance of this class in Python the name property contains random characters instead of the given name.
#include <Python.h>
#include <stdio.h> //printf debugging
#include <stdlib.h> //free
#include "structmember.h"
typedef struct {
PyObject_HEAD
char* name; //allocated and freed by Python
int year;
float maxGas;
} cars_Car;
static int Car_init(cars_Car* self, PyObject* args, PyObject* kwargs){
/*
//Method #1
char* tmp;
// v- Note the &
if(!PyArg_ParseTuple(args, "sif", &tmp, &self->year, &self->maxGas)){
return -1;
}
self->name = (char*)malloc( sizeof(char) * (strlen(tmp) + 1) );
sprintf(self->name, "%s", tmp);
printf("Given name: %s\n", self->name);
//Works
*/
//Method #2
// v- Note the &
if(!PyArg_ParseTuple(args, "sif", &self->name, &self->year, &self->maxGas)){
return -1;
}
printf("Given name: %s\n", self->name); // Works, but repr() and name/getName() are broken
return 0;
}
static void Car_dealloc(cars_Car* self){
//free(self->name); //For Method #2 in init()
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* Car_repr(cars_Car* self){
return PyUnicode_FromFormat("<Car name=\"%s\" year=%d tankSize=%SL>",
self->name, self->year, Py_BuildValue("f", self->maxGas) /* %f not supported, so we convert it to a Python string */ );
}
static PyObject* Car_new(PyTypeObject* type, PyObject* args, PyObject* kwargs){
cars_Car* self;
self = (cars_Car*)type->tp_alloc(type, 0);
self->name = NULL;
self->year = 0;
self->maxGas = 0.0f;
return (PyObject*)self;
}
/* Methods */
static PyObject* Car_getName(cars_Car* self, PyObject* args){
return Py_BuildValue("s", self->name);
}
static PyObject* Car_getYear(cars_Car* self, PyObject* args){
return Py_BuildValue("i", self->year);
}
static PyObject* Car_getTankSize(cars_Car* self, PyObject* args){
return Py_BuildValue("f", self->maxGas);
}
static PyMethodDef Car_methods[] = {
{"getName", (PyCFunction)Car_getName, METH_NOARGS,
"Get the car's name.",
},
{"getYear", (PyCFunction)Car_getYear, METH_NOARGS,
"Get the car's year.",
},
{"getTankSize", (PyCFunction)Car_getTankSize, METH_NOARGS,
"Get the car's tank size.",
},
{NULL}
};
static struct PyMemberDef Car_members[] = {
{"name", T_STRING, offsetof(cars_Car, name), READONLY, "Car name"},
{"year", T_INT, offsetof(cars_Car, year), READONLY, "Car year"},
{"maxGas", T_FLOAT, offsetof(cars_Car, maxGas), READONLY, "Car maxGas"},
{NULL}
};
static PyTypeObject cars_CarType = {
PyVarObject_HEAD_INIT(NULL, 0)
"cars.Car", /* tp_name */
sizeof(cars_Car), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)Car_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)Car_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Cars objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Car_methods, /* tp_methods */
Car_members, /* tp_members */
NULL, /* tp_getset */
NULL, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Car_init, /* tp_init */
0, /* tp_alloc */
Car_new, /* tp_new */
0, /* tp_free */
0 /* tp_is_gc */
};
static PyModuleDef modcars = {
PyModuleDef_HEAD_INIT,
"cars",
"Example module that creates an extension type.",
-1,
NULL, NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_Cars(void) {
PyObject* m;
cars_CarType.tp_new = PyType_GenericNew;
if (PyType_Ready(&cars_CarType) < 0)
return NULL;
m = PyModule_Create(&modcars);
if (m == NULL)
return NULL;
Py_INCREF(&cars_CarType);
PyModule_AddObject(m, "Car", (PyObject *)&cars_CarType);
return m;
}
As you can see, I mentioned 2 different methods in the Car_init function.
When using the first method, I get the following result:
>>> import Cars
>>> x = Cars.Car("The Big Car", 2020, 4.2)
Given name: The Big Car #printf() works
>>> x
<Car name="????" year=2020 tankSize=4.199999809265137L #??? - bunch of random characters
I'm not sure what's causing this, although my guess is that my code is probably writing to some memory address where it's not supposed to. It also looks like there's a floating point precision error.
Interestingly when I directly call getName() or try to access the name attribute, it works.
>>> Cars.Car("The Big Car", 2020, 4.2).name
'The Big Car'
>>> Cars.Car("The Big Car", 2020, 4.2).getName()
'The Big Car'
>>> repr(Cars.Car("The Big Car", 2020, 4.2))
'<Car name="The Big Car" year=2020 tankSize=4.199999809265137L>'
If I switch to the second method everything works fine. I'm not sure why using a temporary variable helps. Also my code doesn't write anything to name, except when initialising it. Everywhere else it's just being read. I also thought about the garbage collector, maybe it's freeing name?
The documentation for the s argument says
A pointer to an existing string is stored in the character pointer variable whose address you pass
Implicitly this pointer is only valid while the existing object is valid (i.e. possibly only until the args tuple is freed).
For your first example that's fine - you allocate new memory with malloc and copy from it. You do that during your initial function call so you know the args tuple and all its contents still exists. You need to remember to free the memory of course.
For your second example you just take a pointer to some memory owned by something else. Keeping a pointer to the memory doesn't do anything to tell Python to keep the memory valid. Therefore the memory is valid during Car_init but most likely invalid shortly after that.

Matlab S-Function crashing when set to dynamically sized

i have following problem. I have created a S-Function which should read a matrix from a text file, where the output size of the output port is not known and therefore set as dynamically sized. Matlab is then crashing. When setting for fixed size, there is no problem. I hope someone could help me out
#define S_FUNCTION_NAME Data_Input
#define S_FUNCTION_LEVEL 2
/*---- Define size of input ports ---------------------------------------------------*/
#define OUTPUTSIZE 50
/*-----------------------------------------------------------------------------------*/
#include <stdio.h>
#include "simstruc.h"
int_T in;
/*---- Define data types ------------------------------------------------------------*/
typedef struct SBufferData
{
real32_T data[50];
int32_T number;
} SBuffer;
/*==== mdlCheckParameters ===========================================================*/
#undef MDL_CHECK_PARAMETERS /* Change to #undef to remove function */
#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
static void mdlCheckParameters(SimStruct *S)
{
}
#endif /* MDL_CHECK_PARAMETERS */
/*===================================================================================*/
/*=== mdlInitializeSizes ============================================================*/
static void mdlInitializeSizes(SimStruct *S)
{
ssSetNumSFcnParams(S,1); /* number of expected parameters */
ssSetSFcnParamTunable(S, 0, 0); /* sets parameter 1 to be non-tunable */
ssSetSFcnParamTunable(S, 1, 0); /* sets parameter 2 to be non-tunable */
ssSetNumContStates(S,0); /* number of continuous states */
ssSetNumDiscStates(S,0); /* number of discrete states */
ssSetNumInputPorts(S,0); /* number of input ports */
ssSetNumOutputPorts(S,1); /* number of output ports */
ssSetOutputPortWidth(S,0,DYNAMICALLY_SIZED); /* first output port width */
ssSetOutputPortDataType(S,0,SS_SINGLE); /* first output port data type */
ssSetNumSampleTimes(S,0); /* number of sample times */
ssSetNumRWork(S,0); /* number real work vector elements */
ssSetNumIWork(S,0); /* number int_T work vector elements */
ssSetNumPWork(S,1); /* number ptr work vector elements */
ssSetNumModes(S,0); /* number mode work vector elements */
ssSetNumNonsampledZCs(S,0); /* number of nonsampled zero crossing */
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
return; /* Parameter mismatch reported by the Simulink engine*/
}
}
/*===================================================================================*/
/*==== mdlInitializeSampleTimes =====================================================*/
static void mdlInitializeSampleTimes(SimStruct *S)
{
real_T dSampleTime=(mxGetPr(ssGetSFcnParam(S,0))[0]);
ssSetSampleTime(S, 0, dSampleTime);
ssSetOffsetTime(S, 0, 0.0);
}
/*===================================================================================*/
/*==== mdlStart =====================================================================*/
#define MDL_START /* Change to #undef to remove function */
#if defined(MDL_START)
static void mdlStart(SimStruct *S)
{
FILE *fp;
int_T i, index=0;
SBuffer *buffer;
float temp;
/*---- Retrieve pointer to pointers work vector -------------------------------------*/
void **PWork = ssGetPWork(S);
buffer = (SBuffer *)malloc(OUTPUTSIZE * sizeof(SBuffer));
PWork[0] = (void *)buffer;
/*---- Read from text-file ----------------------------------------------------------*/
fp = fopen("myfile.txt", "r");
while(feof(fp)==0)
{
fscanf(fp,"%f",&temp);
buffer -> data[index] = temp;
index++;
}
buffer -> number = (int32_T) index;
fclose(fp);
}
#endif /* MDL_START */
/*===================================================================================*/
/*==== mdlOutputs ===================================================================*/
static void mdlOutputs(SimStruct *S, int_T tid)
{
/*---- Get input ports --------------------------------------------------------------*/
real_T *y1=(real_T *)ssGetOutputPortSignal(S,0);
int_T i;
SBuffer *buffer;
/*---- Retrieve pointer to pointers work vector -------------------------------------*/
void **PWork = ssGetPWork(S);
buffer = PWork[0];
for (i = 0; i < buffer->number; i++)
{
y1[i] = buffer->data[i];
}
}
/*===================================================================================*/
/*==== mdlTerminate =================================================================*/
static void mdlTerminate(SimStruct *S)
{
SBuffer *buffer;
/*---- Retrieve pointer to pointers work vector -------------------------------------*/
void **PWork = ssGetPWork(S);
buffer = PWork[0];
/*---- Deallocate structure 'info' and 'buffer' -------------------------------------*/
free(buffer);
}
/*===================================================================================*/
/*==== Required S-function trailer ==================================================*/
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif
/*===================================================================================*/

Calling C++ from Swift - what is the equivalent of std::vector<T>

I'm calling a C++ function from Swift via a bridging header following SwiftArchitect's example. The signature for the C++ function is this:
long GrabberInitializeAndProcess(
unsigned char* pbInPixels,
int inStride,
unsigned char* pbOutPixels,
int outStride,
int width,
int height,
Point mqTopLeft,
Size mqSize,
std::vector<PolylineElement> * pForegroundMarks,
std::vector<PolylineElement> * pBackgroundMarks,
void* pGrabberState );
(N.B. Point, Size, and PolylineElement are local C++ structs.) What signature do I use in my Objective-C++ wrapper for std::vector<T>?
You are using vector as pointer. It's very good when you need use it in Swift.
You can use void* instead:
long GrabberInitializeAndProcess(
unsigned char* pbInPixels,
int inStride,
unsigned char* pbOutPixels,
int outStride,
int width,
int height,
Point mqTopLeft,
Size mqSize,
void * pForegroundMarks,
void * pBackgroundMarks,
void* pGrabberState );
And perform typecasting in implementation.
Or if you need type safety, you can white:
typedef struct _vectorOfPolylineElement *vectorOfPolylineElementPtr;
long GrabberInitializeAndProcess(
unsigned char* pbInPixels,
int inStride,
unsigned char* pbOutPixels,
int outStride,
int width,
int height,
Point mqTopLeft,
Size mqSize,
vectorOfPolylineElementPtr pForegroundMarks,
vectorOfPolylineElementPtr pBackgroundMarks,
void* pGrabberState );
And in implementation:
typedef struct _vectorOfPolylineElement
{
std::vector<PolylineElement> val;
} *vectorOfPolylineElementPtr;
And if you actually don't need vector in GrabberInitializeAndProcess, just it elements you can work with memory:
long GrabberInitializeAndProcess(
unsigned char* pbInPixels,
int inStride,
unsigned char* pbOutPixels,
int outStride,
int width,
int height,
Point mqTopLeft,
Size mqSize,
PolylineElement * pForegroundMarks,
size_t foregroundMarksCount,
PolylineElement * pBackgroundMarks,
size_t backgroundMarksCount,
void* pGrabberState );

How High the Pin of Parallel Port

/* Necessary includes for drivers */
#include <linux/init.h>
//#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h> /* printk() */
#include <linux/slab.h> /* kmalloc() */
#include <linux/fs.h> /* everything... */
#include <linux/errno.h> /* error codes */
#include <linux/types.h> /* size_t */
#include <linux/proc_fs.h>
#include <linux/fcntl.h> /* O_ACCMODE */
#include <linux/ioport.h>
#include <asm/system.h> /* cli(), *_flags */
#include <asm/uaccess.h> /* copy_from/to_user */
#include <asm/io.h> /* inb, outb */
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Nikunj");
/* Function declaration of parlelport.c */
int parlelport_open(struct inode *inode, struct file *filp);
int parlelport_release(struct inode *inode, struct file *filp);
ssize_t parlelport_read(struct file *filp, char *buf, size_t count, loff_t *f_pos);
ssize_t parlelport_write(struct file *filp, char *buf, size_t count, loff_t *f_pos);
void parlelport_exit(void);
int parlelport_init(void);
/* Structure that declares the common */
/* file access fcuntions */
struct file_operations parlelport_fops = {
read : parlelport_read,
write : parlelport_write,
open : parlelport_open,
release : parlelport_release
};
/* Driver global variables */
/* Major number */
int parlelport_major = 61;
/* Control variable for memory */
/* reservation of the parallel port*/
int port;
module_init(parlelport_init);
module_exit(parlelport_exit);
int parlelport_init(void)
{
int result;
/* Registering device */
result = register_chrdev(parlelport_major, "parlelport", &parlelport_fops);
if (result < 0)
{
printk("<1>parlelport: cannot obtain major number %d\n",parlelport_major);
return result;
}
/* Registering port */
port = check_region(0x378, 1);
if (port)
{
printk("<1>parlelport: cannot reserve 0x378\n");
result = port;
goto fail;
}
request_region(0x378, 1, "parlelport");
printk("<1>Inserting parlelport module\n");
return 0;
fail:
parlelport_exit();
return result;
}
void parlelport_exit(void)
{
/* Make major number free! */
unregister_chrdev(parlelport_major, "parlelport");
/* Make port free! */
if (!port)
{
release_region(0x378,1);
}
printk("<1>Removing parlelport module\n");
}
int parlelport_open(struct inode *inode, struct file *filp)
{
/* Success */
return 0;
}
int parlelport_release(struct inode *inode, struct file *filp)
{
/* Success */
return 0;
}
ssize_t parlelport_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
/* Buffer to read the device */
char parlelport_buffer;
/* Reading port */
parlelport_buffer = inb(0x378);
/* We transfer data to user space */
copy_to_user(buf,&parlelport_buffer,1);
/* We change the reading position as best suits */
if (*f_pos == 0)
{
*f_pos+=1;
return 1;
}
else
{
return 0;
}
}
ssize_t parlelport_write( struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
char *tmp;
/* Buffer writing to the device */
char parlelport_buffer;
tmp=buf+count-1;
copy_from_user(&parlelport_buffer,tmp,1);
/* Writing to the port */
outb(parlelport_buffer,0x378);
return 1;
}
this is the code of parallel port device driver and this is my first c code for that.
Please help me to solve the below problem
i have successfully compile the code and create the .ko file successfully and successfully load in the ubuntu 9.10 OS but thee is no high or low the pin so please help me
How you are checking answer?? After installed module do
dmesg
Actually you can not acquire region at 0x378. Because by default system allocate this one to parport0.
Do cat /proc/ioports so you will find that at 0x378 there is parport0.
You can directly write on that address (0x378), without using that checking and requesting.
My suggestion is that don't directly go in complex form. In write function just write
outb(0x378,1) and check (by inserting hardware having LEDs) LED on/off on data pins.

Array of int at the output of a mex file

I am trying to create a mex function whose entry is an integer and whose output is an array of integer.
So the function looks like: int *myFunction(unsigned int N).
In the mexFunction, I declare a variable *variab of type int and then
N = mxGetScalar(prhs[0]);
/* assign a pointer to the output */
siz= 2*ceil(log(1.0*N)/log(2.0)-0.5)+1;
plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL);
vari = (int*) mxGetPr(plhs[0]); */
/* Call the subroutine. */
vari = myFunction(N);
mexPrintf("The first value is %d\n", vari[0]);
The thing is the first value is the correct one (and the other ones were checked and were correct as well) but when I call the routine mxFunction(16), I get only 0's as output.
I guess it is because my output is an array of int but I don't know how to solve the problem. Any hint?
Cheers.
Matlab deals with doubles by default. You can easily cast them in your mex function like the following example based on your code snippet. I have made a myFunction that performs a demo algorithm. Rather than return a data type, I make it a void function and pass it a pointer to the output so that it can populate it . . .
/*************************************************************************/
/* Header(s) */
/*************************************************************************/
#include "mex.h"
#include "math.h"
/*************************************************************************/
/*the fabled myFunction */
/*************************************************************************/
void myFunction(unsigned int N, unsigned int siz, double* output)
{
int sign = 1;
for(int ii=0; ii<siz; ++ii)
{
output[ii] = (double)(ii * sign + N);
sign *= -1;
}
}
/*************************************************************************/
/* Gateway function and error checking */
/*************************************************************************/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
/* variable declarations */
unsigned int siz;
double N;
/* check the number of input and output parameters */
if(nrhs!=1)
mexErrMsgTxt("One input arg expected");
if(nlhs > 1)
mexErrMsgTxt("Too many outputs");
N = mxGetScalar(prhs[0]);
/* assign a pointer to the output */
siz= 2*ceil(log(1.0*N)/log(2.0)-0.5)+1;
plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL);
myFunction(N, siz, mxGetPr( plhs[0]) );
}