cuda1.cu

#include <iostream>

using namespace std ;

# define DELLEXPORT extern "C" __declspec(dllexport)

__global__ void kernel(long* answer = 0){
    *answer = threadIdx.x + (blockIdx.x * blockDim.x);
}

DELLEXPORT void resoult(long* h_answer){

    long* d_answer = 0;
    
    cudaMalloc(&d_answer, sizeof(long));

    kernel<<<10,1000>>>(d_answer);
    cudaMemcpy(&h_answer, d_answer, sizeof(long), cudaMemcpyDeviceToHost);
        cudaFree(d_answer);
}

主要的py公司

import ctypes
import numpy as np

add_lib = ctypes.CDLL(".\\a.dll")
resoult= add_lib.resoult
resoult.argtypes = [ctypes.POINTER(ctypes.c_long)]

x = ctypes.c_long()

print("R:",resoult(x))

print("RV: ",x.value)

print("RB: ",resoult(ctypes.byref(x)))

python输出:0

cuda输出:2096

我基于c语言实现,没有任何问题,但在cuda模式下,我有一个问题,如何才能获得正确的输出值

谢谢

推荐答案

cudaMemcpy is expecting pointers for dst and src.
In your function resoult, h_answer is a pointer to a long allocated by the caller.
Since it's already the pointer where the data should be copied to, you should use it as is and not take it's address by using &h_answer.

因此,您需要将您的cudaMemcpy更改为:

cudaMemcpy(&h_answer, d_answer, sizeof(long), cudaMemcpyDeviceToHost);

收件人:

cudaMemcpy(h_answer, d_answer, sizeof(long), cudaMemcpyDeviceToHost);

Python相关问答推荐

如何避免Chained when/then分配中的Mypy不兼容类型警告?

无法通过python-jira访问jira工作日志(log)中的 comments

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

将pandas Dataframe转换为3D numpy矩阵

当独立的网络调用不应该互相阻塞时,'

numpy卷积与有效

启动带有参数的Python NTFS会导致文件路径混乱

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

使用Python查找、替换和调整PDF中的图像'

Pandas:填充行并删除重复项,但保留不同的值

使用SeleniumBase保存和加载Cookie时出现问题

一个telegram 机器人应该发送一个测验如何做?""

如何从比较函数生成ngroup?

删除特定列后的所有列

你能把函数的返回类型用作其他地方的类型吗?'

当输入是字典时,`pandas. concat`如何工作?

浏览超过10k页获取数据,解析:欧洲搜索服务:从欧盟站点收集机会的微小刮刀&

Pandas:计数器的滚动和,复位

将相应的值从第2列合并到第1列(Pandas )

多索引数据帧到标准索引DF