简体   繁体   中英

Calling C++ CUDA code from python

I want to call a function written in CUDA(C++) from python and pass to it numpy arrays as input and get output arrays from this function. Is this possible? This is the sole objective of this question.

ps : As I understand if such a function were to be made into a proper program and compiled into an executable then it could be called from python as a shell command. However how could I pass and get arrays as inputs and outputs without using files?

PyCuda is provided by nvidia. it's also very easy to use. check it out https://developer.nvidia.com/pycuda

I suppose you want something like that:

import pycuda.autoinit
import pycuda.driver as drv
import numpy

from pycuda.compiler import SourceModule
mod = SourceModule("""
__global__ void multiply_them(float *dest, float *a, float *b)
{
  const int i = threadIdx.x;
  dest[i] = a[i] * b[i];
}
""")

multiply_them = mod.get_function("multiply_them")

a = numpy.random.randn(400).astype(numpy.float32)
b = numpy.random.randn(400).astype(numpy.float32)

dest = numpy.zeros_like(a)
multiply_them(
        drv.Out(dest), drv.In(a), drv.In(b),
        block=(400,1,1), grid=(1,1))

print dest-a*b

有一些库可能对这类任务有所帮助,但PyCuda似乎与你所描述的最接近。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM