Python:在AcANDA(Windows)中构建C++模块作为共享对象而不是扩展 假设您有一个C++函数,您想在Python中使用Python。CPP extern "C" int fun(int i) { return i*2; }
然后可以使用下面的setup.pyPython:在AcANDA(Windows)中构建C++模块作为共享对象而不是扩展 假设您有一个C++函数,您想在Python中使用Python。CPP extern "C" int fun(int i) { return i*2; },python,module,anaconda,Python,Module,Anaconda,然后可以使用下面的setup.py from distutils.core import setup, Extension module1 = Extension('fun', sources = ['src/fun.cpp'],include_dirs = ['src/']) setup (name = 'fun', version = '1.0', description = 'This is a fun package', ext_mod
from distutils.core import setup, Extension
module1 = Extension('fun', sources = ['src/fun.cpp'],include_dirs = ['src/'])
setup (name = 'fun',
version = '1.0',
description = 'This is a fun package',
ext_modules = [module1],
packages = ['fun'])
然后在这个有趣的软件包中,您可以有以下内容
import ctypes
fun = ctypes.cdll.LoadLibrary(__path__[0]+"/../fun.so").fun
fun.restype = ctypes.c_int
fun.argtype = ctypes.c_int
所以你可以像这样使用它
>>import fun
>>fun.fun(2)
>>4
:
这在Linux中工作得非常好,但是当我在Windows上使用Anaconda尝试这一点时,首先链接器要求我提供一个initfun符号,这意味着它正在尝试构建一个python扩展,而不仅仅是构建一个共享对象。有人知道如何更改setup.py或Anaconda设置来构建共享对象并将其与ctypes.cdll.LoadLibrary函数一起使用吗
提前感谢。我终于使用了这个解决方案。它并没有尽可能的干净,因为它试图以一种不安全的方式找到蟒蛇的路径
from distutils.core import setup, Extension
from sys import platform as _platform
if _platform == "linux" or _platform == "linux2":
module1 = Extension('fun/fun', sources = ['src/fun.cpp','src/cochlea.cpp'],include_dirs = ['src/'], extra_compile_args=['-Ofast','-flto','-march=native','-funroll-loops'] )
setup (name = 'fun',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1],
packages = ['fun'])
elif _platform == "darwin":
module1 = Extension('fun/fun', sources = ['src/fun.cpp','src/cochlea.cpp'],include_dirs = ['src/'], extra_compile_args=['-Ofast','-flto','-march=native','-funroll-loops'] )
setup (name = 'fun',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1],
packages = ['fun'])
elif _platform == "win32":
import sys
for a in sys.path:
f = a.find('Anaconda')
if f!=-1:
path = a[:f+9]
import os
os.system("gcc.bat -mdll -O -Wall -Isrc/ -I"+path+"include -I"+path+"PC -c src/fun.cpp -o fun.o -Ofast -flto -march=native -funroll-loops")
os.system("g++.bat -shared -s fun.o -o fun.dll")
setup (name = 'fun',
version = '1.0',
description = 'This is a demo package',
package_data={'fun': ['fun.dll']},
packages = ['fun'])