我试图在JCuda中使用JCuda来从/src/main/resources加载一个vectorAdd.ptx文件。守则如下:
cuModuleLoad(module, getClass.getResource("vectorAdd.ptx").getPath())但是cuModuleLoad()没有接收到这个文件。只有当我传递ptx file的绝对路径时,它才能工作。但是我希望ptx file随编译jar files一起提供。有什么办法可以做到这一点吗?
发布于 2015-12-15 17:56:11
function in JCuda是到相应 function in CUDA的直接映射。它需要一个文件名作为第二个参数。
问题是:cuModuleLoad无法加载PTX文件,因为PTX文件对于数据自动化系统根本不存在!PTX文件隐藏在JAR文件中。
当您使用someClass.getResource()从JAR文件获得资源时,它将指向JAR文件中的资源。当你做这样的事情
System.out.println(getClass().getResource("vectorAdd.ptx").getPath());然后运行这个(作为一个JAR文件),然后您将看到这样的输出:
file:/U:/YourWorkspace/YourJarFile.jar!/vectorAdd.ptx注意.jar!部分:这个路径不是,而是一个真正文件的路径,而是JAR中资源的路径。
为了从JAR加载PTX文件,您必须将PTX文件从JAR读取到Java侧的byte[]数组中,然后将其传递给 function of JCuda (对应于 function of CUDA)。
下面是一个示例,它将PTX数据从JAR文件加载到字节数组中,表示可以传递给cuModuleLoadData的以零结尾的字符串。
import static jcuda.driver.JCudaDriver.cuCtxCreate;
import static jcuda.driver.JCudaDriver.cuDeviceGet;
import static jcuda.driver.JCudaDriver.cuInit;
import static jcuda.driver.JCudaDriver.cuModuleGetFunction;
import static jcuda.driver.JCudaDriver.cuModuleLoadData;
import static jcuda.runtime.JCuda.cudaDeviceReset;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import jcuda.driver.CUcontext;
import jcuda.driver.CUdevice;
import jcuda.driver.CUfunction;
import jcuda.driver.CUmodule;
import jcuda.driver.JCudaDriver;
public class JCudaPtxInJar
{
public static void main(String args[]) throws IOException
{
// Initialization
JCudaDriver.setExceptionsEnabled(true);
cuInit(0);
CUdevice device = new CUdevice();
cuDeviceGet(device, 0);
CUcontext context = new CUcontext();
cuCtxCreate(context, 0, device);
// Read the PTX data into a zero-terminated string byte array
byte ptxData[] = toZeroTerminatedStringByteArray(
JCudaPtxInJar.class.getResourceAsStream(
"JCudaVectorAddKernel.ptx"));
// Load the module data
CUmodule module = new CUmodule();
cuModuleLoadData(module, ptxData);
// Obtain a function pointer to the "add" function
// and print a simple test/debug message
CUfunction function = new CUfunction();
cuModuleGetFunction(function, module, "add");
System.out.println("Got function "+function);
cudaDeviceReset();
}
/**
* Read the contents of the given input stream, and return it
* as a byte array containing the ZERO-TERMINATED string data
* from the stream. The caller is responsible for closing the
* given stream.
*
* @param inputStream The input stream
* @return The ZERO-TERMINATED string byte array
* @throws IOException If an IO error occurs
*/
private static byte[] toZeroTerminatedStringByteArray(
InputStream inputStream) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[8192];
while (true)
{
int read = inputStream.read(buffer);
if (read == -1)
{
break;
}
baos.write(buffer, 0, read);
}
baos.write(0);
return baos.toByteArray();
}
}编译它并将其打包到JAR (当然与/resources/JCudaVectorAddKernel.ptx PTX文件一起)将允许您启动程序并从JAR中的PTX获取示例函数。
https://stackoverflow.com/questions/34259441
复制相似问题