簡體   English   中英

無法使用SWIG創建的python訪問C ++擴展模塊及其方法

[英]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.pygfg_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM