对于我正在处理的项目,我需要从 C++ 调用 Python 函数,该函数具有 PyTorch 张量作为输入。在寻找实现这一点的方法时,我发现使用名为THPVariable_Wrap的函数(我找到链接 1和链接 2的信息)可以将 C++ Pytorch 张量转换为 PyObject,它可以用作调用 Python 的输入功能。但是,我尝试通过将头文件直接包含在我的代码中来导入此函数,但这将始终返回错误LNK2019,调用该函数时,具有以下描述:
严重性代码描述项目文件行抑制状态错误 LNK2019 未解析的外部符号“__declspec(dllimport) struct _object * __cdecl THPVariable_Wrap(class at::TensorBase)”(_ imp ?THPVariable_Wrap@@YAPEAU_object@@VTensorBase@at@@@Z) 引用在函数主 pythonCppTorchExp C:\Users\MyName\source\repos\pythonCppTorchExp\pythonCppTorchExp\example-app.obj 1
我相信问题在于我如何在我的 C++ 文件中导入THPVariable_Wrap函数。但是,我仍然对 C++ 不太熟练,并且这方面的信息有限。除了 Pytorch,我还使用 Boost 调用 Python,我使用的是 Microsoft Visual Studio 2019 (v142),使用 C++ 14。我在下面发布了我使用的代码。
C++ 文件
#include <iostream>
#include <iterator>
#include <algorithm>
#include <boost/python.hpp>
#include <Python.h>
#include <string.h>
#include <fstream>
#include <boost/filesystem.hpp>
#include <torch/torch.h>
#include <torch/csrc/autograd/python_variable.h> /* The header file where */
namespace python = boost::python;
namespace fs = boost::filesystem;
using namespace std;
int main() {
string module_path = "Path/to/python/folder";
Py_Initialize();
torch::Tensor cppTensor = torch::ones({ 100 });
PyRun_SimpleString(("import sys\nsys.path.append(\"" + module_path + "\")").c_str());
python::object module = python::import("tensor_test_file");
python::object python_function = module.attr("tensor_equal");
PyObject* castedTensor = THPVariable_Wrap(cppTensor) /* This function call creates the error.*/;
python::handle<> boostHandle(castedTensor);
python::object inputTensor(boostHandle);
python::object result = python_function(inputTensor);
bool succes = python::extract<bool>(result);
if (succes) {
cout << "The tensors match" << endl;
}
else {
cout << "The tensors do not match" << endl;
}
}
蟒蛇文件
import torch
def tensor_equal(cppTensor):
pyTensor = torch.ones(100)
areEqual = cppTensor.equal(pyTensor)
return areEqual