首页 > 解决方案 > 不允许从 __host__ __device__ 函数调用 __host__ 函数

问题描述

我正在尝试将推力与 Opencv 类一起使用。最终的代码会更复杂,包括使用设备内存,但这个简单的例子没有成功构建。

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>

//#include <thrust/copy.h>
#include <thrust/remove.h>
#include <cuda.h>
#include <cuda_runtime.h>

#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/cudaarithm.hpp>

#include <iostream>

struct is_zero
{
  __host__  __device__ 
  bool operator()(const cv::KeyPoint x)
  {
    return x.response  == 0.0;
  }
};


int main(void){

cv::KeyPoint h_data[5]; 


h_data[0]=  cv::KeyPoint(cv::Point2f(3,4),0.3);
h_data[1]=  cv::KeyPoint(cv::Point2f(2,6),0.3);
h_data[2]=  cv::KeyPoint(cv::Point2f(1,1),0.3);
h_data[3]=  cv::KeyPoint(cv::Point2f(2,8),0.3);
h_data[4]=  cv::KeyPoint(cv::Point2f(2,6),0.3);


h_data[0].response=0.3;
h_data[1].response=0.0;
h_data[2].response=0.5;
h_data[3].response=0.0;
h_data[4].response=0.6;


cv::KeyPoint *new_data_end = thrust::remove_if(h_data, h_data + 5, is_zero());  //this does not work

} 

如您所见,我什至没有将主机内存变量传递给设备内存或任何东西。

当我尝试构建时,我得到了

/usr/local/cuda/include/thrust/system/cuda/detail/par.h(141): warning: calling a __host__ function("cv::Point_<float> ::Point_") from a __host__ __device__ function("cv::KeyPoint::KeyPoint") is not allowed

/usr/local/cuda/include/thrust/system/cuda/detail/par.h(141): warning: calling a __host__ function("cv::Point_<float> ::Point_") from a __host__ __device__ function("cv::KeyPoint::KeyPoint [subobject]") is not allowed

/usr/local/cuda/include/thrust/system/cuda/detail/par.h(141): warning: calling a __host__ function("cv::Point_<float> ::operator =") from a __host__ __device__ function("cv::KeyPoint::operator =") is not allowed

如何将推力 remove_if 与 opencv 类一起使用?

cv::KeyPoint(我的计划是将来使用 remove_if 和数组)

标签: c++cudathrust

解决方案


正如评论中所指出的,对于您显示的代码,您会收到警告,并且可以安全地忽略此警告。

用于 CUDA 设备代码:

为了使 C++ 类在 CUDA 设备代码中可用,任何将在 CUDA 设备代码中显式或隐式使用的相关成员函数都必须使用装饰器进行标记。__device__(有一些例外情况,例如这里不适用的默认构造函数。)

您尝试使用的 OpenCV 类 ( cv::KeyPoint) 不符合在设备代码中使用的这些要求。它不会按原样使用。

可能有几个选项:

  1. cv::KeyPoint使用您自己编写的提供类似功能的某些类来重铸您的工作,以便进行适当的设计和装饰。

  2. 也许看看用 CUDA 构建的 OpenCV 是否在这里有一个替代版本(正确设计/装饰)(我猜它可能没有)

  3. 重写 OpenCV 本身,考虑到所有必要的设计更改,以允许cv::KeyPoint该类在设备代码中可用。

  4. 作为建议 1 的变体,将相关数据复制.response到一组单独的类或只是一个裸数组,然后根据它进行选择工作。在那里完成的选择工作可用于“过滤”原始数组。


推荐阅读