Passing data to and from C++ code using a python driver
<p>I am trying to pass arrays to a c++ function from a python driver.  One of the arrays I am passing to the c++ function is a results array.  I know the data is passing to the code correctly, but seems to be truncating on the way back.  I'm loosing my precision after the decimal.  Any ideas where I went wrong?  Below is a simplified version of the code, and the resultant output.</p>

<p>python code:</p>

<pre><code>import ctypes
from ctypes import *

def get_calculate_windows():
    dll = ctypes.CDLL('./cppFunctions.so', mode=ctypes.RTLD_GLOBAL)
    func = dll.calculate_windows
    func.argtypes = [POINTER(c_float), POINTER(c_float), c_size_t]
    return func

def calculate_windows(data, answer, size):
    data_p = data.ctypes.data_as(POINTER(c_float))
    answer_p = answer.ctypes.data_as(POINTER(c_float))

    __calculate_windows(data_p, answer_p, size)


###### MAIN FUNCTION #####

data = np.array(myData, dtype=np.float32)
ans = np.array(myAnswer, dtype=np.float32)

print ans[:10]
calculate_windows(data, ans, myLength)
print ans[:10]
</code></pre>

<p>c++ code:</p>

<pre><code>extern "C" {

    void calculate_windows(float *h_data, float *result, size_t size ) {

        for (int i=0; i&lt;size; i++ ) {
            result[i]=i/10;
        }

    }
}
</code></pre>

<p>output:</p>

<pre><code>[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
</code></pre>

<p>What the output SHOULD be:</p>

<pre><code>[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.0  0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9]
</code></pre>

<blockquote>
  <p>I know the data is passing to the code correctly, but seems to be truncating on the way back. I'm losing my precision after the decimal. Any ideas where I went wrong?</p>
</blockquote>

<p>You are using integer division instead of floating-point division.</p>

<p>You can fix this by using:</p>

<pre><code>result[i] = i / 10.;
</code></pre>

<p>Instead of:</p>

<pre><code>result[i] = i / 10;
</code></pre>

python c++ floating-point ctypes