c++ - 创建 pybind11 模块以返回随机火炬张量:未定义符号错误
问题描述
我正在尝试使用 pybind11 创建一个 python 模块来生成一个火炬张量。我在 colaboratory 做这个。wget https://download.pytorch.org/libtorch/cu102/libtorch-win-shared-with-deps-1.7.1.zip
首先,我从and 获取 libtorch 库 unzip libtorch-win-shared-with-deps-1.7.1.zip
。我也是git clone https://github.com/pybind/pybind11.git
。
我有两个 .cpp 文件。第一个是testLibtorch.cpp,其中包含:
#include <torch/torch.h>
#include <torch/extension.h>
using torch::Tensor;
Tensor test(int num) {
Tensor tensor1 = torch::randn({4, 3});
return tensor1;
}
PYBIND11_MODULE(testLibtorch, m) {
m.doc() = "hello world"; // optional module docstring
m.def("test", &test, "A function giving torch tensor");
}
第二个是testExe.cpp,其中包含:
#include <torch/torch.h>
#include <torch/extension.h>
#include <iostream>
int main(){
std::cout << torch::randn({4, 3}) << std::endl;
}
我正在编写自己的CMakeLists.txt:
project(torchlibtest)
cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_STANDARD 14)
include_directories(/content/libtorch)
set(CMAKE_PREFIX_PATH "/content/libtorch/share/cmake/Torch")
find_package(Torch REQUIRED)
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
add_subdirectory(pybind11)
pybind11_add_module(testLibtorch testLibtorch.cpp)
target_link_libraries(testLibtorch PRIVATE "${TORCH_LIBRARIES}")
target_link_libraries(testLibtorch ${MY_LIBRARIES})
set_property(TARGET testLibtorch PROPERTY CXX_STANDARD 14)
add_executable(testExe testExe.cpp)
target_link_libraries(testExe PRIVATE "${TORCH_LIBRARIES}")
if (MSVC)
file(GLOB TORCH_DLLS "${TORCH_INSTALL_PREFIX}/lib/*.dll")
add_custom_command(TARGET example-app
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${TORCH_DLLS}
$<TARGET_FILE_DIR:example-app>)
endif (MSVC)
然后我成功地cmake和make。但是,当我尝试导入我的模块 testLibtorch 时,我收到此错误:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-9-9855a0c0e93c> in <module>()
1 import torch
----> 2 import testLibtorch
3 print(testLibtorch.test(4))
ImportError: /content/build/testLibtorch.cpython-36m-x86_64-linux-gnu.so: undefined symbol: _Z16THPVariable_WrapN2at6TensorE
我怀疑我可能无法从 Torch 导入类和函数,但来自testExe.cpp的可执行文件似乎工作正常。将欣赏问题的解决方案,以及我正在尝试做的任务的建议和想法。
解决方案
推荐阅读
- bootstrap-4 - How to add Bootstrap 4 validation design into select2
- java - 从 USats.getForegroundAppPackagename() 返回的字符串值
- typescript - TypeScript:使用异步加载的数据扩展数组中的对象
- typescript - 为什么箭头函数名称必须是 const/let?
- javascript - 如果将复合组件传递给 Waypoint,为什么需要用 React.forwardRef 包装它?
- database - 如何在mysql中存储隐藏值
- mysql - 帖子的多重评分系统(喜欢,爱,明星)
- javascript - 如何将对象中的键与给定的字符串匹配?
- amp-html - 规范 amp 页面上的 amp-ad(adsense 和 GAM)
- django - 如何用用户模型的某些字段更新继承用户模型的模型的字段?