'How to pass python 2d matrix to C function ctypes
I tried to pass my matrix from python to C++ based on ctypes to multiply by 2 but I could not get the result that I want because it says inf instead.
C code (DLL)
float mult(float *x,int rowLen,int colLen)
{
int rows = rowLen;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
*(x+ i*rows + j) = 2*(x+ i*rows + j));
cout << "Test : " << *(x+ i*rows + j);
}
}
return *(x);
}
Python Code
import numpy as np
import ctypes
from ctypes.util import *
matrix = [
[1, 0.23, 0.25],
[4.34, 1, 1.11],
[3.93, 0.90, 1],
]
ptr = (ct.c_double*3*3)()
for i in range(3):
for j in range(3):
ptr[i][j] = matrix[i][j]
print(ptr[i][j])
c_lib = ctypes.CDLL('testDll.dll')
c_lib.mult.restype = ctypes.c_float
answer = c_lib.mult(ptr, 3, 3)
print(f"{answer}")
` I am not sure why the shell shows 'inf' and why C did not print the calculation in every iteration. Please advised me how to overcome this problem?
Solution 1:[1]
The main problem was the Python array used c_double instead of c_float. Additional changes to make it compile (please post a compilable example with your question next time):
test.c
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
API float mult(float *x,int rowLen,int colLen)
{
int rows = rowLen;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < colLen; j++) {
x[i*rows + j] *= 2;
}
}
return *x;
}
test.py
import ctypes as ct
matrix = [[1, 0.23, 0.25],
[4.34, 1, 1.11],
[3.93, 0.90, 1]]
ptr = (ct.c_float*3*3)() # was incorrectly c_double
for i in range(3):
for j in range(3):
ptr[i][j] = matrix[i][j]
#print(ptr[i][j])
c_lib = ct.CDLL('./test')
c_lib.mult.restype = ct.c_float
answer = c_lib.mult(ptr, 3, 3)
print(answer)
for row in ptr:
print(' '.join([f'{x:.2f}' for x in row]))
Output:
2.0
2.00 0.46 0.50
8.68 2.00 2.22
7.86 1.80 2.00
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
