0

I want to use C to speed up computation.

I have already read the following info:

How to pass a 2d array from Python to C?

I want to pass float 2d numpy array to c.

c code is below

#include <stdio.h>

double main(double **fp2)
{
    int i;
    for ( i=0; i < 10; i++ )
        printf("%d, %d\n", fp2[i][0], fp2[i][1]);

}

python code is below

import ctypes
import os
import sys
cwd = os.path.dirname(os.path.realpath(__file__))
#
import numpy as np


DLL_NAME = "./simple_print.{:s}".format("dll" if sys.platform[:3].lower() == "win" else "so")

C_double_Ptr = ctypes.POINTER(ctypes.c_double)
C_double_PtrPtr = ctypes.POINTER(C_double_Ptr)

my = ctypes.CDLL(DLL_NAME)
myFunc = my.main
myFunc.argtypes = [C_double_PtrPtr]
myFunc.restype = ctypes.c_double

np_array_2d = np.array(np.random.rand(10,2), dtype=np.float64)

print(np_array_2d)


ct_arr = np.ctypeslib.as_ctypes(np_array_2d)
C_double_PtrArr = C_double_Ptr * ct_arr._length_
ct_ptr = ctypes.cast(C_double_PtrArr(*(ctypes.cast(row, C_double_Ptr) for row in ct_arr)), C_double_PtrPtr)
res = myFunc(ct_ptr)



print("\n{0:s} returned: {1:f}".format(myFunc.__name__, res))

But result is different between python and C.

python
[[0.66088702 0.95406219]
 [0.18609616 0.89634064]
 [0.0174235  0.52141446]
 [0.4939825  0.67305432]
 [0.45147721 0.13951316]
 [0.16937601 0.57228122]
 [0.57805704 0.98001207]
 [0.99983335 0.63249494]
 [0.51295051 0.08450172]
 [0.20974118 0.7960613 ]]
C
-1960361805, 1835376087
-1248799216, -1885421307
1842847712, 1615298041
-940448502, 903669117
-1443205772, 1053507048
-190023196, -1244975300
2034696801, 1139364725
-2064136264, 161766169
766548286, -1425458880
-2106453208, -1975869746

main returned: 0.000000

Please help me...

1 Answers1

0

What you did when printing in c was two float at a time with a custom format.

Where in python you have used the default printing method for array and float.

Then the main change is that you got integer printed in c:

It is because you have used %d (meant for integer) rather than %f (meant for float).

Assuming that your python and c code are working correctly.

You need to change one of them:

If you choose to change python:

replace:

print(np_array_2d)

with:

    for f, s in np_array_2d:
        print(f, s, sep=", ")

if you choose to change the c code:

double main(double **fp2) {
    int i;
    printf("[");
    for ( i=0; i < 10; i++ )
        printf("[%f, %f]\n", fp2[i][0], fp2[i][1]);
    printf("]");
}

You will need to change the %d into %f anyway

I also strongly recommend changing the name of the c fonction, it probably wont be a problem this time but it could in a lot of case.

LTBS46
  • 205
  • 1
  • 10