Я попытался передать свою матрицу из python в C++ на основе ctypes для умножения на 2, но я не смог получить желаемый результат, потому что вместо этого он говорит inf.
C-код (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
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}")
` Я не уверен, почему оболочка показывает «inf» и почему C не печатает расчет на каждой итерации. Подскажите, пожалуйста, как победить эту проблему?
Основная проблема заключалась в том, что массив Python использовал c_double
вместо c_float
. Дополнительные изменения для его компиляции (пожалуйста, опубликуйте компилируемый пример с вашим вопросом в следующий раз):
тест.с
#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]))
Выход:
2.0
2.00 0.46 0.50
8.68 2.00 2.22
7.86 1.80 2.00