首页 > 解决方案 > 使用 SWIG 和 Visual Studio 2017 在 python 中导入 C++ DLL

问题描述

我目前正在尝试将 c++ dll 导入 python 脚本。现在我想导入一个非常简单的 dll,只有一个函数(用于测试)。当我通过如何从 Visual Studio 2010 使用 SWIG 创建 DLL 中的详细说明进行工作时,有两个链接错误我不太明白。

在第 25 步之前一切正常(现在需要额外的预处理器定义generated _wrapper.cxx来绕过strcpy)。一旦我尝试构建项目(一切编译都没有问题),我从 VS 得到这个输出:

my_f.obj : error LNK2005: "int __cdecl cubes(int const &)" (?cubes@@YAHAEBH@Z) already defined in my_f.obj
Creating library C:\work\example64\my_f\x64\Release\_my_f.lib and object
C:\work\example64\my_f\x64\Release\_my_f.exp
C:\work\example64\my_f\x64\Release\_my_f.pyd : fatal error LNK1169: one or more multiply defined symbols found
Done building project "my_f.vcxproj" -- FAILED.

我正在使用 64 位系统,安装的 python (3.6) 是 x64 版本(虽然没有调试)。

我的.i文件如下所示:

%module cube

%{
#include "my_f.cpp"
%}

%include my_f.cpp

.cpp带有代码的文件如下:

#include "stdafx.h"
int cubes(const int &a)
{
    return a * a*a;
}

标签: pythonc++dllwrapperswig

解决方案


我想我找到了解决方案。

因为我没有.h文件,所以有一个函数声明,但没有定义。添加头文件或将函数声明为inline函数有助于解决此编译错误。


推荐阅读