![](/img/trans.png)
[英]How to pass string parameters to C++ function using ctypes, python
[英]How to pass numpy ndarrays to a c++ function using ctypes?
我花了两天的时间弄清楚如何将ndarrays传递给c / c ++,但仍然找不到任何可以正常工作的东西。
每件事都被记录下来,令人困惑。
我找到的唯一教程在https://scipy.github.io/old-wiki/pages/C%2B%2B_Extensions_that_use_NumPy_arrays.html中 。
但是,当我尝试运行python代码“ myextension.py”时,它会引发ImportError:没有名为numpyndarrays的模块。
我不想使用cython或boost或python C-API。
#include <iostream>
#include "ndarray.h"
extern "C" {
Ndarray<double, 3> myfunc(numpyArray<double> array1)
{
Ndarray<double,3> a(array1);
std::cout<<a.getShape(0); //this prints 0 and it means somthing is wrong
for (int i = 0; i < a.getShape(0); i++)
{
for (int j = 0; j < a.getShape(1); j++)
{
for (int k = 0; k < a.getShape(2); k++)
{
a[i][j][k] = 2.0 * a[i][j][k];
std::cout<<a[i][j][k]<<' '<<i<<' '<<j<<' '<<k<<'\n';// prints nothing because a.getShape(0) is 0.
}
}
}
return a;
}
}
首先,当我尝试编译此代码时,编译器引发致命错误,原因是它找不到ndarray.h。
我从https://scipy.github.io/old-wiki/pages/ndarray2e5c.h?action=AttachFile&do=get&target=ndarray.h手动下载了ndarray.h文件
import numpy as np
import numpy.ctypeslib as ct
mylib = ct.load_library('n', '.')
def myfunc(array1):
return mylib.myfunc(array1.ctypes) # I also tried ct.as_ctypes(array1) instead of array1.ctypes with no success
a = np.ones((2,2,2)).astype(np.double)
myfunc(a)
此代码正确加载了共享库,主要问题是如何将numpy ndarray转换为共享库的输入结构。
我还需要知道如何将共享库的输出转换为numpy ndarray。
我发现使用numpy C-API是将numpy数组传递给c ++的最简单方法。
该文档可以在https://docs.scipy.org/doc/numpy/reference/c-api.html上找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.