所以我使用 python 来调用共享 C++ 库中的方法。我在将 numpy 2D 数组转换为 C++ 2D 短裤数组作为函数输入时遇到问题。我创建了一个展示该问题的玩具示例。随意编译并尝试一下!
这是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)
这是 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);
}
}
我使用以下命令编译:
g++ -fPIC -Wall -Wextra -shared -o libsoexample.so soexample.cpp
当我运行 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
我该如何正确纠正这个不幸TypeError
?