2015-09-19 61 views
2

我已經在C++中構建了一個應用程序(「Checkyrs」),現在我正在做一些外部使用Checkyrs的大部分內容的東西,但是使用Python 3構建。在我的空閒時間,所以它不需要是Python 3,但這是我的偏好。)使用Swig和distutils構建Python 3的擴展

要獲得python和C++之間的接口,我使用SWIG和python distutils軟件包。我已經構建了一個包含Checkyrs所需內容的動態庫,並且使用我提到的工具成功構建了一個Python擴展(「checkyrsai」)。我已經在Python 2.7中對它進行了測試,並且它可以正常工作,我需要的所有C++類和函數都可以正常工作。

但我的偏好是與Python 3工作,而我可以建立與Python 3擴展我無法成功加載:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import checkyrsai 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Users/chris/Documents/Programming/eggyolk/checkyrsai.py", line 28, in <module> 
    _checkyrsai = swig_import_helper() 
    File "/Users/chris/Documents/Programming/eggyolk/checkyrsai.py", line 24, in swig_import_helper 
    _mod = imp.load_module('_checkyrsai', fp, pathname, description) 
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/imp.py", line 243, in load_module 
    return load_dynamic(name, filename, file) 
ImportError: dlopen(/Users/chris/Documents/Programming/eggyolk/_checkyrsai.so, 2): Symbol not found: __ZN4Game11ExecuteMoveERKSt6vectorI8PositionSaIS1_EE 
    Referenced from: /Users/chris/Documents/Programming/eggyolk/_checkyrsai.so 
    Expected in: flat namespace 
in /Users/chris/Documents/Programming/eggyolk/_checkyrsai.so 

我的過程中建立的擴展名(Python的2 )是:

swig -c++ -python checkyrsai.i 
python setup.py build_ext --inplace 

在我的setup.py文件看起來是這樣的:

from distutils.core import setup, Extension 
import os 

os.environ["CC"] = "g++" 

checkyrsai = Extension('_checkyrsai', 
        sources = ['checkyrsai_wrap.cxx','../checkyrs/checkyrs/ai.cpp'], 
        include_dirs = ['/usr/local/include','../checkyrs/checkyrs'], 
        libraries = ['Checkyrs'], 
        library_dirs = ['../checkyrs/Build/Products/Release/','/usr/local/lib'], 
        extra_compile_args = ['-std=c++11'] 
        ) 


setup (name = 'checkyrs', 
     version = '1.0', 
     description = 'checkyrs', 
     ext_modules = [checkyrsai]) 

由於I S上面的援助,這完美的作品。從這個角度,我可以打開我的Python(2.7)解釋,

import checkyrsai 

和關閉我去與我的新玩具玩。

當試圖建立Python 3中我使用幾乎一模一樣的過程,只是加入的Python的3個標誌爲SWIG和運行的distutils通過的Python 3:

swig -c++ -python -py3 checkyrsai.i 
python3 setup.py build_ext --inplace 

這個貫穿編譯成功和生成擴展名,但當我嘗試

import checkyrsai 

我得到上面引用ImportError符號未找到問題。

我不會在Python 2和Python 3版本之間以任何方式更改我的代碼或setup.py腳本。該符號指的是應該在我的libCheckyrs.dylib中找到的方法。它顯然在那裏可用,因爲它在我使用Python 2.7擴展時被成功地使用 - 但是當我爲Python 3擴展時似乎沒有被發現。有沒有人有我的錯誤的建議?

回答

1

我最終通過更改我正在鏈接的C++庫的XCode項目設置來解決此問題。

具體而言,將「C++語言方言」設置更改爲「C++ [-std = C++ 11]」,即我在distutils的extra_compile_args設置中指定的相同版本。以前它是GNU ++ 11,因此符號不匹配,因爲命名空間中存在不匹配(std :: vector與std :: __ 1 :: vector)。

與該改變現在我快樂地和成功地能夠從Python 3的叫我的C++代碼

我真的不明白爲什麼它沒有在Python 2.7的工作,因爲它使用所有相同的distutils設置,指定相同的C++版本以及針對相同C++庫的鏈接。如果任何人有解釋,我很樂意聽到它。

相關問題