Reputation: 1695
fI try to wrap a c function using ctypes, for example:
#include<stdio.h>
typedef struct {
double x;
double y;
}Number;
double add_numbers(Number *n){
double x;
x = n->x+n->y;
printf("%e \n", x);
return x;
}
I compile the c file with the option
gcc -shared -fPIC -o test.so test.c
to a shared library.
The Python code looks like this:
from ctypes import *
class Number(Structure):
_fields_=[("x", c_double),
("y", c_double)]
def main():
lib = cdll.LoadLibrary('./test.so')
n = Number(10,20)
print n.x, n.y
lib.add_numbers.argtypes = [POINTER(Number)]
lib.add_numbers.restypes = [c_double]
print lib.add_numbers(n)
if __name__=="__main__":
main()
The printf statement in the add_numbers function returns the expected value of 3.0e+1, but the return value of the lib.add_numbers function is always zero. I don't see the error, any Idea?
Upvotes: 3
Views: 1167
Reputation: 114781
Change this:
lib.add_numbers.restypes = [c_double]
to this:
lib.add_numbers.restype = c_double
Note that it is restype
, not restypes
.
Upvotes: 9