[英]Python C++ extension with SWIG - calling a function by importing module
[英]Cannot access C++ extension module and its methods from python created using SWIG
在visual studio 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 <= 1)
return 1;
else
return (n * fact(n - 1));
}
//find mod
int my_mod(int n, int m)
{
return(n % m);
}
//gfg.h
#pragma once
long long int fact(long long int n);
int my_mod(int n, int 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_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
執行此操作后,它在項目目錄中生成了_gfg_d.cp37-win_amd64.pyd
文件。
從CMD import gfg
時,顯示以下錯誤。
我試圖從gfg.h
訪問fact
方法gfg.h
是否缺少某些內容?
python37的Release版本使用python37.dll,但您嘗試使用Python的Debug版本,它正在尋找python37_d.dll。 使用適用於Python 3.7的python.exe
運行它,它將起作用。
如果要調試構建,請使用:
setup.py build_ext --debug --inplace
擴展名將為_gfg.cp37-win_amd64.pyd
(或其他平台上的某些變體)。 它必須被命名為_gfg.pyd
的發行版本或_gfg_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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.