gpt4 book ai didi

c# - 在 CUDAfy 的结构中传递数组

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:43 25 4
gpt4 key购买 nike

使用 VS 2012、.NET 4.5、64 位和 CUDAfy 1.12,我有以下概念证明

using System;
using System.Runtime.InteropServices;
using Cudafy;
using Cudafy.Host;
using Cudafy.Translator;

namespace Test
{
[Cudafy(eCudafyType.Struct)]
[StructLayout(LayoutKind.Sequential)]
public struct ChildStruct
{
[MarshalAs(UnmanagedType.LPArray)]
public float[] FArray;
public long FArrayLength;
}

[Cudafy(eCudafyType.Struct)]
[StructLayout(LayoutKind.Sequential)]
public struct ParentStruct
{
public ChildStruct Child;
}

public class Program
{
[Cudafy]
public static void KernelFunction(GThread gThread, ParentStruct parent)
{
long length = parent.Child.FArrayLength;
}

public static void Main(string[] args)
{
var module = CudafyTranslator.Cudafy(
ePlatform.x64, eArchitecture.sm_35,
new[] {typeof(ChildStruct), typeof(ParentStruct), typeof(Program)});
var dev = CudafyHost.GetDevice();
dev.LoadModule(module);

float[] hostFloat = new float[10];
for (int i = 0; i < hostFloat.Length; i++) { hostFloat[i] = i; }

ParentStruct parent = new ParentStruct
{
Child = new ChildStruct
{
FArray = dev.Allocate(hostFloat),
FArrayLength = hostFloat.Length
}
};

dev.Launch(1, 1, KernelFunction, parent);

Console.ReadLine();
}
}
}

当程序运行时,我在 dev.Launch 上收到以下错误:

类型“Test.ParentStruct”不能作为非托管结构进行编码;无法计算有意义的大小或偏移量。

如果我从 ChildStruct 中删除 float 组,它会按预期工作。

我过去曾在 C/C++/Cli 和 CUDA C 中工作过,我知道错误的性质。此错误的一些解决方案建议使用 MarshalAsSize 参数手动设置结构大小,但由于结构中类型的多样性,这是不可能的。

我查看了生成的 .cu 文件,它正在将 float 组生成为 float *,这正是我所期望的。

有没有办法将结构中的数组传递给内核?如果没有什么是最好的第二种选择?这个问题在 CUDA C 中不存在,它只存在是因为我们是从 CLR 编码的。

最佳答案

我花了很多时间阅读 CUDAfy 的源代码,看看是否有解决这个问题的方法。

CUDAfy 试图让 .NET 开发人员的工作变得过于简单,并使他们远离 IntPtr 和其他指针概念。然而,抽象级别使得如果不对该库的工作方式进行重大重构,就很难找到这个问题的答案。

无法在结构中发送 float 组是一个阻碍。我最终对 CUDA 运行时执行了 PInvoke 而没有使用 CUDAfy。

关于c# - 在 CUDAfy 的结构中传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16340278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com