python - 如何将 python 2d matrix 传递给 C 函数 ctypes

我试图将我的 matrix 从 python 传递到基于 ctypes 的 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 没有在每次迭代中打印计算。请告诉我如何克服这个问题?

回答1

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

测试.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;
}

测试.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

相似文章

c++ - 模板类的标量乘法不起作用

当我进行标量乘法时,会发生此错误。我正在使用模板类对矩阵执行这些操作。我一直试图掌握这些概念,但我似乎失败了。任何帮助表示赞赏。main.cpp里面的main函数Matrix<int,3,3>m4;M...

随机推荐

最新文章