我在Visual Studio 2012中有一个CUDA项目,其中包含一个函数,我想在VC ++项目中使用它,感谢Mr.Crovella,我将CUDA项目目标从.exe更改为项目属性/配置属性/常规/配置类型中的.dll。 这是我定义函数的头文件:
内核.h
#ifndef KERNEL_H
#define KERNEL_H
#ifdef __cplusplus
extern "C" {
#endif
void __declspec(dllexport) cuspDsolver(int *rowOffset, int *colIndex, double *values , double *X, double *rhs, int size, int nnz);
#ifdef __cplusplus
}
#endif
#endif
这是我的函数实现:
kernel.cu
#include "kernel.h"
#include <cusp/krylov/cg.h>
#include <cusp/csr_matrix.h>
#include <cusp/hyb_matrix.h>
#include <cusp/gallery/poisson.h>
#include <cusp/io/matrix_market.h>
#include <cuspprint.h>
#include <fstream>
#include <conio.h>
#include <math.h>
#include <iostream>
#include <windows.h>
using namespace std;
void cuspDsolver(int *rowOffset, int *colIndex, double *values , double *X, double *rhs, int size, int nnz)
{
cusp::csr_matrix<int,double,cusp::device_memory> A(size,size,nnz);
for (int i = 0; i < (size+1); i++)
{
A.row_offsets[i] = rowOffset[i];
}
for (int i = 0; i < nnz; i++)
{
A.column_indices[i] = colIndex[i];
A.values[i] = values[i];
}
cusp::array1d<double,cusp::device_memory> XX(size,0.);
cusp::array1d<double,cusp::device_memory> B(size,0.);
for (int i = 0; i < size; i++)
{
B[i] = rhs[i];
}
cusp::krylov::cg(A,XX,B);
for (int i = 0; i < size; i++)
{
X[i] = XX[i];
}
}
这是我的VC++项目(它是一个静态库system.lib项目,将在quickMain.exe中使用)以及我如何尝试使用我的.dll文件:
系统库
#ifdef __cplusplus
extern "C" {
#endif
void __declspec ( dllimport ) cuspDsolver(int *rowOffset, int *colIndex, double *values , double *X, double *rhs, int size, int nnz);
#ifdef __cplusplus
}
#endif
.
.
.
.
.
.
.
int
ProfileSPDLinDirectSolver::solve(void){
.
.
.
.
cuspDsolver(rowOffset,colIndex,values,answer,rightHandSide,theSize,nnz);
.
.
.
.
}
当我想构建这个项目时(我确实将我的 dll 文件复制到解决方案目录和解决方案/调试目录)我收到这些错误,请告诉我我在创建或使用此 dll 时是否做错了什么?
error LNK2019: unresolved external symbol __imp__cuspDsolver referenced in function "public: virtual int __thiscall ProfileSPDLinDirectSolver::solve(void)" (? solve@ProfileSPDLinDirectSolver@@UAEHXZ) 2012ProjectsArdalan_12Win32projquickMainsystem.lib(ProfileSPDLinDirectSolver.obj)
error LNK1120: 1 unresolved externals C:UsersAdministratorDocumentsVisual Studio 2012ProjectsArdalan_12Win32binquickMain.exe 1
从 kernel.cu 创建 dll 后,您将生成一个 dll 库文件(例如,kernel.dll
)和一个 dll 库导入文件(例如,kernel.lib
)。
在希望使用该 dll 的任何项目的 VC/VS 项目定义中,必须链接到 dll 库导入文件:
nvcc ... -lkernel
将此库添加到项目定义的过程与添加任何其他库的过程相同。 确保kernel.dll
和kernel.lib
也位于指定的链接器路径上。
而且,在运行时,您的kernel.dll
库需要与可执行文件位于同一目录中,或者在 Windows dll 加载路径中。
您需要在函数声明上添加__declspec(dllexport)修饰符。此修饰符告知编译器和链接器从 DLL 导出函数或变量以供其他应用程序使用。将以下内容添加到您的内核.h,
#pragma once
#ifdef KERNEL_EXPORTS
#define KERNEL_API __declspec(dllexport)
#else
#define KERNEL_API __declspec(dllimport)
#endif
extern "C" KERNEL_API void cuspDsolver(int *rowOffset, int *colIndex, double *values ,double *X, double *rhs, int size, int nnz);
详情请参阅:https://learn.microsoft.com/zh-tw/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=vs-2019#to-add-a-header-file-to-the-dll