How to parse void* to PyObject - c

I want to write a wrapper for my C function as I want to call it from python code.So my wrapper function is
static PyObject* my_func_wrapper(PyObject *self, PyObject *args)
{
PyObject* obj_Ptr = my_func();
return Py_BuildValue('O', obj_Ptr);
}
My C my_func() has no params, and return MyClass pointer converted to (void *).
When I run my setup.py script I'm getting this
warning: passing argument 1 of ‘Py_BuildValue’ makes pointer from integer without a cast [-Wint-conversion]
Py_BuildValue('O', obj_Ptr);
and when I call my_func_wrapper from python I'm getting Seg.Fault Error in return line.
How can I fix this?
Thanks.

Here is the prototype of Py_BuildValue:
PyObject *Py_BuildValue(char *format, ...);
So the first argument should be "O" and not 'O'.
I'm not sure about you second arg either : you are using my_func() result instead of getting a pointer to this function.

Related

Error when Compiling CPython: C2440 'function': cannot convert from 'PyObject' to PyObject *'

I'm new to using CPython (and C as well) and I was trying to create an extension module to calculate nCk. However, I'm coming across this really annoying error when compiling. Here's my code:
PyObject* combination(PyObject* n, PyObject* k){
PyObject* output = ONE;
return PyNumber_TrueDivide(factorial(n), PyNumber_Multiply(factorial(k), factorial(PyNumber_Subtract(n, k))));
}
static PyObject* BezierCurve_combination(PyObject* self, PyObject* args){
PyObject n, k;
if (!PyArg_ParseTuple(args, "OO", &n, &k))
return NULL;
/* This return statement is line 60*/
return Py_BuildValue("O", combination(n, k));
}
And here is the error message:
(60): error C2440: 'function': cannot convert from 'PyObject' to 'PyObject *'
(60): warning C4024: 'combination': different types for formal and actual parameter 1
(60): warning C4024: 'combination': different types for formal and actual parameter 2
What is causing this error? A similar program works really well for a factorial function definition (it contains just 1 PyObject* argument.) How can I fix this?
You can never have a PyObject in your program like that. They're always pointers to PyObjects.
Use PyObject *n, *k; - or, if in doubt,
PyObject *n;
PyObject *k;
Furthermore, you must always check the return value of each and every function in a Python exception, excepting if you're just returning it from your function. Thus you may not write
return PyNumber_TrueDivide(factorial(n),
PyNumber_Multiply(factorial(k), factorial(PyNumber_Subtract(n, k))));
You can only write
return PyNumber_TrueDivide(dividend, divisor);
For the inner calls you must check that they're not NULL separately, and if they are it signifies an exception that you must handle, or throw out (by returning NULL from your function).

C ADT function pointer as parameter?

I have a function in an ADT:
Pgroup new_group(int size, void (*foo)(void *));
In my other class I have this function to send in:
void foo(Pstruc x);
x is a pointer to a struct. When I try to call new_group however, I receive an error "expected 'void (*)(void )' but argument is of type 'void ()(struct struc_ *)". This is how I've been calling it:
Pgroup group = new_group(num, &foo);
Any suggestions?
You can cast the argument to the correct type to get rid of the diagnostic:
Pgroup group = new_group(num, (void (*)(void *)) foo);
Note that this is not portable as C does not guarantee that the representation between different pointers is the same. The best would be to use types that match in their declarations.
You can rewrite your original function from void foo(Pstruc x); to void foo(void* x);.
Or convert its type: (void(*)(void*))foo.

How do I declare a function to be used as a function pointer in c?

I am confused with function pointer declaration.
I have an api abc() which takes an argument as so:
void abc(void (*my_func)(void *p), int, int)
If I want to pass my function as an argument to that api, I am declaring it in my .h file:
void (*xyz)(void *p)
and defining as:
void *(xyz)(void *p){
statements;
}
but this throws an error. Please correct me.
you just need to declare it:
void xyz(void *p);
with the implementation the same way.
When you pass it into your api, the type system figures out it out automatically:
abc(xyz,someint,anotherint);
The (*xyz) means that it is a function pointer.
Function pointers are best handled with typedefs. So it is guaranteed that there is nothing wrong.
I would do the following:
// define a type for the function (not its pointers, as you can often read)
typedef void my_func_t(void *p);
void abc(my_func_t*, int, int);
// declaration in order to be type-safe - impossible if only the pointer would be typedef'd
my_func_t my_func_impl;
// definition:
void my_func_impl(void *p)
{
do_something_with(p);
}
and then you can call your abc() with abc(my_func_impl, 47, 11). You can put a & before my_func_impl there in order to point out that it is the function address you wish to obtain, but it is optional.
An alternative would be to write
typedef void (*my_func_p)(void *p);
and use my_func_p instead of my_func_t *, but this has the disadvantage that you cannot write my_func_t my_func_impl;.
Why would you want to do that?
Well, if, by any coincidence or accident, the function definition or the typedef is changed, they won't match any longer, but the collision is not declared as error, but only as warning (Mismatch pointer). OTOH, my_func_t my_func_impl; serves as a kind of prototype, which causes a function header mismatch, which is an error.
Simply declare and define your function as you would any other:
void xyz(void *p);
void xyz(void *p){
// ...
}
and pass a pointer to the API:
abc(xyz, 42, 7);
Function names are automatically interpreted as function pointers where appropriate. You can also explicitly take the address of the function, if brevity isn't your thing:
abc(&xyz, 42, 7);
If I understood correctly, you want xyz to be the function that is passed to abc, right?
As the argument my_func indicates, you have a pointer to a function that takes void * as argument and returns void
type (*func_pointer)(type, type, type, .......)
^ ^ ^ ^ ^ ^
| | | | | |
| | | argument types
| | pointer name
| This is a function pointer
return type
Therefore, you need to declare xyz as:
void xyz(void *p);
And the same in implementation:
void xyz(void *p){
statements;
}
What you are doing wrong is that, the line you wrote in the .h file defines a function pointer, named xyz. The function pointer has no value, because you never wrote xyz = some_function;
What you have written in the source file is a function, also with name xyz that takes a void * as input and returns a void *, instead of void which was your intention.
Maybe this helps you get less confused:
When you write int *x;, x is a pointer to int. Then you can have int y; that doesn't have an extra * and write x = &y;.
It's the same with functions. If you have void (*funcptr)(void *p);, then all you need is a function that says void some_func(void *p){} (again without the extra *) and write funcptr = some_func;. You don't need the & since function names are in fact pointer to the function. You could put it to be more explicit though.
The first argument of 'abc' is the pointer of function returning 'void' and having 'void *' as an argument...
So your code should look like:
void
myFunc (void *)
{
// ... my statements
}
...
abc (myFunc, 10, 20);
This works
void abc(void* (*my_func)(void*), int a, int b) {
my_func(0);
}
void *(xyz)(void *p) {}
int main() {
abc(xyz, 0, 0);
return 0;
}
When you write void (*my_func)(void *p) it means pointer to function, that returns void
And void (*my_func)(void *p) it means pointer to function, that returns pointer

C: PThread_create Parsing Char[] parameter to function

Hallo All,
I have this method:
void *readFileLocal(char filename[]){
.....
}
Now i want to start this method a a thread:
char input[strlen(argv[1])];
strcpy(input,argv[1]);
pthread_t read,write;
pthread_create(&read, NULL, &readFileLocal, &input);
But during compilation it gives this warning:
file.c:29: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type
/usr/include/pthread.h:227: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(char *)’
How can I parse an char array to my funcation over pthread_create without this warning ?
Thanks for helpt
Just use this:
pthread_create(&read, NULL, readFileLocal, input);
And consider changing your function's signature to:
void *readFileLocal(void *fileName) { }
When you are passing a pointer to function (like the one you are using in readFileLocal parameter) you don't need to put &.
Also, when you have an array (like input in your case) you don't need & since in C arrays can be used as pointers already.
Functions for threads need to be prototyped:
void *func(void *argv);
As with all void pointers you then need to interpret ("cast") the pointer to a meaningful entity. You readFileLocal functions then becomes:
void *readFileLocal(void *argv)
{
char *fname = argv; // Cast to string
// Rest of func
}

Strange C construction encountered in academic paper

The code states:
void (* log_msg)(char *msg)
=printf;
void change_and_log(int *buffer, int offset, int value){
buffer[offset] = value;
log_msg("changed");
}
I'm most concerned with the first part:
Firstly, what does the signature void (* log_msg)(char *msg) mean? Is this code simply mapping the function log_msg to printf? In that case, why is the function name (* log_msg) and not simply log_msg?
void (* log_msg)(char *msg) is actually a function pointer. You could view this as
typedef void (*LoggerFunctionPointer)(char* msg);
LoggerFunctionPointer log_msg = printf;
Yes, it maps log_msg to printf, but no, log_msg isn't a function, but a pointer that points to a function printf.
Using a function pointer has the advantage that the log_msg can be switched at runtime. For example, you could provide a switch in the interface that
void no_log_msg(char* msg) {}
...
if (enable_debug) {
log_msg = printf;
} else {
log_msg = no_log_msg;
}
then, without changing other source code, all logging can be inhibited.
(BTW, the sample code is incorrect because the signature of printf is int printf(const char*, ...). To avoid the implicit cast, log_msg should be declared as
int (*log_msg)(const char*, ...) = printf;
)
It's a function pointer.
The type of a function pointer is R (*)(Args...), where R and Args... are replaced with the return type and arguments, if any. It is read as "a pointer to a function that takes arguments Args... and returns R."
Your code would read easier as:
// print_function is a type that is a function pointer
typedef void (*print_function)(char *msg);
// log_msg is a variable of the type print_function: it points to a function
print_function log_msg = printf; // point to printf
And later, it's just calling that function via a function pointer.
The top two lines are establishing a function pointer (hence the *), the function is named log_msg, and it's then set to point to printf - after which a call to log_msg ends up calling printf.
log_msg is a function pointer, in particular a "pointer to a function taking a char * and returning void". In this case it's just used as an alias for printf (but could point to any function with the same arguments and return type).
The syntax for function pointers in C can be pretty intimidating at first.

Resources