0

Currently I'm learning about C types. I have a piece of C code. It is not the whole code, but I think the rest is not relevant to share. The sin and cos function are defined above in the original code.

C:

double tan(f) double f;
{
       return sin(f)/cos(f); 

Python:

import ctypes

testlib = ctypes.CDLL('./testlib.so')

testlib.tan.argtypes = ctypes.c_double
teslib.tan.restype = ctypes.c_double

print(testlib.tan(2))

First I didn't use the lines:

testlib.tan.argtypes = ctypes.c_double
teslib.tan.restype = ctypes.c_double

I got an output, but the ouput was 0. I thought that the double value was downcasted to an int.

What I want to achieve is that I send an double from python to C, and C will return me a double.

I'm already familiar with this documentation, but I didn't manage to find the right answer: https://docs.python.org/3/library/ctypes.html

Question: How should I modify my code to get the good output?

Ter

Tim
  • 415
  • 2
  • 10

1 Answers1

0

Since argtypes must be a sequence of types, use e.g. testlib.tan.argtypes = ctypes.c_double, - note the trailing , here

Additional Remarks

  • K&R function definition with separately declared parameter types are outdated, so instead of double tan(f) double f; use double tan(double f)

  • tan is a trigonometric function from the C standard library, so it's better to use a different name

So it could look like:

#include <math.h>

double tan1(double f) {
    return sin(f)/cos(f);
}

Don't forget to also use the name tan1 then on Python side:

testlib.tan1.argtypes = ctypes.c_double,
testlib.tan1.restype = ctypes.c_double

print(testlib.tan1(2))

The result is:

-2.185039863261519
Stephan Schlecht
  • 26,556
  • 1
  • 33
  • 47
  • Thank you very much! To pass one value with Ctypes was practice to grasp the principle of C types. I actually need to process a whole numpy array. But I find it really hard since there is not really a 1:1 example to find online. I posted a new thread: https://stackoverflow.com/questions/64478880/how-to-pass-this-numpy-array-to-c-with-ctypes . If you have the time, would you please give me feedback on how to achieve that goal? @StephanSchlecht – Tim Oct 22 '20 at 09:07