无法访问C++;使用SWIG创建的python扩展模块及其方法
在代码> VisualStudio 2017 中创建了一个空C++ 添加以下文件的C++方法 //gfg.c无法访问C++;使用SWIG创建的python扩展模块及其方法,python,c++,swig,Python,C++,Swig,在代码> VisualStudio 2017 中创建了一个空C++ 添加以下文件的C++方法 //gfg.c #include <stdio.h> #include <math.h> //our header file #include "gfg.h" #define ll long long double myvar = 3.4; // calculate factorial ll int fact(ll int n) { if (n <
#include <stdio.h>
#include <math.h>
//our header file
#include "gfg.h"
#define ll long long
double myvar = 3.4;
// calculate factorial
ll int fact(ll int n)
{
if (n <= 1)
return 1;
else
return (n * fact(n - 1));
}
//find mod
int my_mod(int n, int m)
{
return(n % m);
}
//gfg.i用于游泳
/* file : gfg.i */
/* name of module to use*/
%module gfg
%{
/* Every thing in this file is being copied in
wrapper file. We include the C header file necessary
to compile the interface */
#include "gfg.h"
/* variable declaration*/
double myvar;
%}
/* explicitly list functions and variables to be interfaced */
double myvar;
long long int fact(long long int n1);
int my_mod(int m, int n);
/* or if we want to interface all functions then we can simply
include header file like this -
%include "gfg.h"
*/
为gfg.i文件添加了自定义操作,如下所示,输出文件名为gfg_wrap.c
$(SWIG_PATH)\swig.exe -python gfg.i
在编译gfg.i文件时,它给出了两个输出gfg.py
和gfg\u wrap.c
然后,我创建了具有以下内容的Setup.py
文件
# File : setup.py
from distutils.core import setup, Extension
#name of module
name = "gfg"
#version of module
version = "1.0"
# specify the name of the extension and source files
# required to compile this
ext_modules = Extension(name='_gfg',sources=["gfg.i","gfg.c"])
setup(name=name,
version=version,
ext_modules=[ext_modules])
#C:\Python37\python_d.exe setup.py build_ext --inplace
以自定义操作作为
C:\Python37\python_d.exe setup.py build_ext --inplace
此python目录包含swig.exe
执行此操作后,它在项目目录中生成了一个\u gfg\u d.cp37-win\u amd64.pyd
文件
当从CMD输入gfg时,显示以下错误
我试图从
gfg.h
访问fact
方法,我是否遗漏了什么?Python的发布版本使用了python37.dll,但您试图使用Python的调试版本,而不是python37\u d.dll。用python 3.7的python.exe运行它,它就会工作
如果需要调试生成,请使用:
setup.py build_ext --debug --inplace
扩展名将是\u gfg.cp37-win\u amd64.pyd
(或其他平台上的一些变体)。发布版本必须命名为\u gfg.pyd
,调试版本必须命名为\u gfg\u d.pyd
。我必须手动重命名它才能让它工作。
我没有找到强制使用该名称的选项:
C:\>copy _gfg.cp37-win_amd64.pyd _gfg_d.pyd
1 file(s) copied.
C:\>python_d
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 05:02:23) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import gfg
>>> gfg.fact(5)
120
看起来您为Python解释器构建了它,它与您实际运行的解释器不同。不过,我不太明白写的是什么。可能与python_d.exe不是系统默认的python有关。python37.dll由python的发布版本使用,但您正在尝试使用python的调试版本,该版本正在寻找python37_d.dll。用python 3.7的python.exe运行它,它就会工作。
C:\>copy _gfg.cp37-win_amd64.pyd _gfg_d.pyd
1 file(s) copied.
C:\>python_d
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 05:02:23) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import gfg
>>> gfg.fact(5)
120