【问题标题】:dependencies between compiled modules in pythonpython中编译模块之间的依赖关系
【发布时间】:2011-12-09 18:51:52
【问题描述】:

假设我在一个 python 项目中有两个模块,它们是用 C++ 编写并使用 boost::python 公开的。

mod1.hpp

#ifndef MOD1_HPP
#define MOD1_HPP

#include <boost/python.hpp>

int square(int x);

#endif

mod1.cpp

#include "mod1.hpp"

using namespace boost::python;

int square(int x)
{
    return x*x;
}

BOOST_PYTHON_MODULE (mod1)
{
    def("square",&square);
}

mod2.hpp

#ifndef MOD2_HPP
#define MOD2_HPP

#include <iostream>
#include <boost/python.hpp>
#include "mod1.hpp"

int myfunc(int x);

#endif

mod2.cpp

#include "mod2.hpp"

using namespace boost::python;

int myfunc(int x)
{
    int y = square(x);
    std::cout << y << std::endl;
}

BOOST_PYTHON_MODULE (mod2)
{
    def("myfunc",&myfunc);
}

如您所见,mod2 正在使用 mod1 中定义的函数。在没有 boost::python 包装器和 main 函数的情况下编译,它工作得非常好。

现在是编译脚本

setup.py

#!/usr/bin/python2

from setuptools import setup, Extension

mod1 = Extension('mod1',
                 sources = ['mod1.cpp'],
                 libraries = ['boost_python'])

mod2 = Extension('mod2',
                 sources = ['mod2.cpp'],
                 libraries = ['boost_python'])

setup(name='foo',
      version='0.0',
      description='',
      ext_modules=[mod1,mod2],
      install_requires=['distribute'])

它编译得很好。然后我转到build/lib.linux-i686-2.7 并启动 python2

>>> import mod1
>>> import mod2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: ./mod2.so: undefined symbol: _Z6squarei
>>> 

显然 mod2 没有找到 mod1 存在问题。我该如何解决?如何在 python 项目中定义多个 C 模块并允许它们相互使用?

【问题讨论】:

    标签: c++ python boost-python


    【解决方案1】:

    由于 mod1 是 Python 扩展,干净的方法是像使用任何其他 Python 模块一样使用它:

    object mod1 = import("mod1");
    object square = mod1.attr("square");
    int y = extract<int>(square(x));
    

    【讨论】:

    • 有趣。但这意味着模块之间的任何调用都会增加双层转换,C->python->C ...真的是唯一的方法吗?
    • 好吧,我想您可以将直接 C++ 接口暴露给您的函数,并像其他动态 C++ 库一样链接到 mod1。
    • 这不正是我在我的示例中所做的吗?或者我的 setup.py 文件可能缺少链接时传递的一些参数?
    • mod2 需要链接到 mod1。我不确定您是否可以使用 setup.py 进行构建。我更愿意将共享功能放在单独的纯 C++ 库中(使用 C++ 工具构建)并从 mod1 和 mod2 链接到该库。
    • 您也可以简单地将 mod1.cpp 添加到 mod2 的源列表中
    猜你喜欢
    • 2012-03-09
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 2010-11-12
    相关资源
    最近更新 更多