将2D numpy数组转换为C++ short**?

dil*_*erj 6 c++ python numpy short shared-libraries

所以我使用python来调用共享C++库中的方法.我有一个问题是将numpy 2D数组转换为C++ 2D short函数作为函数输入.我有一个创建了一个展示问题的玩具示例.随意编译并试用!

这是python代码(soexample.py):

# Python imports
from ctypes import CDLL
import numpy as np

# Open shared CPP library:
cpplib=CDLL('./libsoexample.so')
cppobj = cpplib.CPPClass_py()

# Stuck on converting to short**?
array = np.array([[1,2,3],[1,2,3]])
cpplib.func_py(cppobj,array)
Run Code Online (Sandbox Code Playgroud)

这是C++库(soexample.cpp):

#include <iostream>

using namespace std;

class CPPClass
{
  public:
  CPPClass(){}

  void func(unsigned short **array)
  {
      cout << array[0][0] << endl;
  }
};

// For use with python:
extern "C" {
    CPPClass* CPPClass_py(){ return new CPPClass(); }
    void func_py(CPPClass* myClass, unsigned short **array)
    {      
        myClass->func(array);    
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用以下命令编译:

g++ -fPIC -Wall -Wextra -shared -o libsoexample.so soexample.cpp
Run Code Online (Sandbox Code Playgroud)

当我运行python文件时,我收到以下错误:

>> python soexample.py
Traceback (most recent call last):
  File "soexample.py", line 13, in <module>
    cpplib.func_py(cppobj,array)
ctypes.ArgumentError: argument 2: <type 'exceptions.TypeError'>: Don't know how to     convert parameter 2
Run Code Online (Sandbox Code Playgroud)

我该如何正确纠正这个不幸TypeError

gre*_*olf 4

您可以使用ctypes'sc_shortPOINTER来帮助进行中间转换。以下函数将 numpy 数组转换为 C 类型 2darray,可以将其传递到需要short **.

def c_short_2darr(numpy_arr):
  c_short_p = POINTER(c_short)
  arr = (c_short_p * len(numpy_arr) ) ()
  for i in range(len(numpy_arr)):
    arr[i] = (c_short * len(numpy_arr[i]))()
    for j in range(len(numpy_arr[i])):
      arr[i][j] = numpy_arr[i][j]
  return arr
Run Code Online (Sandbox Code Playgroud)

注意,我修改了func_pyCPPClass::func来获取两个额外的参数,即给定数组的宽度和长度。这样,CPPClass::func就可以打印出数组的所有元素:

// ...
void CPPClass::func(unsigned short **array, size_t w, size_t h)
{
    for(size_t i = 0; i < w; ++i)
    {
      for(size_t j = 0; j < h; ++j)
          cout << array[i][j] << ", ";
      cout << '\n';
    }
}
// ...
void func_py(CPPClass *myClass,
             unsigned short **array, 
             size_t w, size_t h)
{
    myClass->func(array, w, h);
}
Run Code Online (Sandbox Code Playgroud)

定义该辅助函数后,以下内容现在应该可以工作:

>>> arr = numpy.array([ [1,2,3], [4,5,6] ])
>>> arr
array([[1, 2, 3],
       [4, 5, 6]])
>>> cpplib.func_py(cppobj, c_short_2darr(arr), 2, 3)
1, 2, 3,
4, 5, 6,
0
Run Code Online (Sandbox Code Playgroud)