如何将 python 二维矩阵传递给 C 函数 ctypes

How to pass python 2d matrix to C function ctypes

我试图根据 ctypes 将我的矩阵从 python 传递到 C++ 以乘以 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}")

` 我不确定为什么 shell 显示 'inf' 以及为什么 C 没有在每次迭代中打印计算。请告诉我如何克服这个问题?

主要问题是 Python 数组使用了 c_double 而不是 c_float。使其编译的其他更改(下次请 post 一个可编译的示例与您的问题):

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]))

输出:

2.0
2.00 0.46 0.50
8.68 2.00 2.22
7.86 1.80 2.00