Using a C function in Python
<p>I've tried all the solutions mentioned on the internet so far nothing worked for me.</p>

<p>I have a python code, to speed it up, I want that my code runs the heavy calculations in a C function.
I already wrote this C function.</p>

<p>Then, to share the library, I did this in the terminal :</p>

<pre><code>gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC myModule.c
</code></pre>

<p>which returns no error. The problem; comes when i try to launch the C function in python. Let's consider the following simple function in C :</p>

<pre><code>int multiplier(int a, int b)
{

int lol = 0;

lol = a*b;

return lol;
}
</code></pre>

<p>I launch python3 (3.5.2), and then :</p>

<pre><code>import ctypes
zelib = ctypes.CDLL("/Users/longeard/Desktop/Codes/DraII/testlib.so",ctypes.RTLD_GLOBAL)
</code></pre>

<p>The library should be ready to use in python by doing :</p>

<pre><code>res = zelib.multiplier(2,3)
</code></pre>

<p>When doing that, it works and python returns </p>

<pre><code>6
</code></pre>

<p>Problem is, that the function i want to use ( the multiplier function I use is just for the example ) is supposed to take floats as input and return a float. But if I now consider the same multiplier function as before but with float :</p>

<pre><code>float multiplier(float a, float b)
{

float lol = 0.0;

lol = a*b;

return lol;
}
</code></pre>

<p>I recompile using gcc, I reimport ctypes and re-do ctypes.CDLL, and I do in python3 :</p>

<pre><code>zelib.multiplier(ctypes.c_float(2),ctypes.c_float(3))
</code></pre>

<p>(the types.c_float are here to convert the 2 in python into a float in C ), python will return :</p>

<pre><code>2
</code></pre>

<p>This is weird because if I add a printf within the function to print lol, python will print :</p>

<pre><code>  6.0
</code></pre>

<p>but still return 2, or 18 sometimes. Even though I printf and return the same variable "lol".</p>

<p>I tried a lot of things, and none of it worked. Do somebody have a idea please ? Thank You.</p>

<p>While @falsetru's answer is the better way of doing it an alternative is to simply write your C function to use doubles.</p>

<p>Floats are automatically promoted to double when  calling a function without a parameter list.</p>

python c python-3.x ctypes