我正在尝试使用 Visual Studio 2018 和 Python 3.7 以及 swig 3.0.12 swig 一个简单的 C++ 类。 我的 C++ 头文件
#ifndef atATObjectH
#define atATObjectH
#include "core/atCoreExporter.h"
#include <string>
//--------------------------------------------------------------------------
using std::string;
class AT_CORE ATObject
{
public:
ATObject();
virtual ~ATObject();
virtual const string getTypeName() const;
};
#endif
atCoreExporter.h:
#ifndef atCoreExporterH
#define atCoreExporterH
#if defined (_WIN32)
#if defined(AT_STATIC)
#define AT_CORE
#else
#if defined(AT_EXPORT_CORE)
#define AT_CORE __declspec(dllexport)
#else
#define AT_CORE __declspec(dllimport)
#endif
#endif
#else
#define AT_CORE
#endif
#endif
我确实创建了一个定义了 AT_EXPORT_CORE 的 DLL。
我正在使用 CMake 生成 swigged pyd 模块。这是接口(interface)文件:
// atexplorer.i
%include "std_string.i"
%include "windows.i"
%module atexplorer
%{
#include "atATObject.h"
%}
//Expose class ATObject to Python
%include "atATObject.h"
这是 CMake 文件
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(atexplorer.i PROPERTIES CPLUSPLUS ON)
SWIG_ADD_LIBRARY(atexplorer LANGUAGE python SOURCES atexplorer.i)
INCLUDE_DIRECTORIES(
.
${ATAPI_ROOT}
${ATAPI_ROOT}/source
${ATAPI_ROOT}/source/core
)
link_directories(${LIBRARY_OUTPUT_PATH})
SWIG_LINK_LIBRARIES (atexplorer
atCore
${PYTHON_LIBRARIES}
)
SET(ATEXPLORER_PACKAGE_DIR site-package)
SET(python_files_path ${CMAKE_BINARY_DIR}/wrappers/python/atexplorer)
INSTALL(
TARGETS _atexplorer
DESTINATION ${ATEXPLORER_PACKAGE_DIR}
COMPONENT python_module
)
INSTALL(
FILES ${python_files_path}/atexplorer.py __init__.py
DESTINATION ${ATEXPLORER_PACKAGE_DIR}
COMPONENT python_module
)
我遇到的问题是导出/导入宏。上面的接口(interface)文件编译失败,我从生成的 SWIG 代码中得到编译错误,如下所示
AT_CORE * temp;
temp = reinterpret_cast< AT_CORE * >(argp);
ATObject = *temp;
其中 AT_CORE 是上面 atCoreExporter.h 中定义的导出/导入宏。
处理这个问题的正确解决方案是什么?
最佳答案
在使用宏之前确保 swig 接口(interface)文件包含宏 header 。我能够通过在 .i 文件中添加“%include”来解决这个问题。
// atexplorer.i
%include "std_string.i"
%include "windows.i"
%module atexplorer
%{
#include "atATObject.h"
%}
//Expose class ATObject to Python
%include "atCoreExporter.h"
%include "atATObject.h"
关于python - SWIG 和 Windows 导出宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49928983/