c++ - Boost Python 中的跨模块依赖关系

标签 c++ python boost extension-modules

假设我有两个定义如下的 boost python 模块。模块 A:

class SomeClass {
public:
    SomeClass() {}
    ~SomeClass() {}
};
BOOST_PYTHON_MODULE(A)
{   
    class_<SomeClass>("SomeClass");
}

和模块 B:

class AnotherClass {
public:
    AnotherClass() {}
    ~AnotherClass() {}
    void func(SomeClass& sp) {}
};
BOOST_PYTHON_MODULE(B)
{   class_<AnotherClass>("AnotherClass")
        .def("func", &AnotherClass::func)
    ;
}

模块 B 依赖于模块 A(即它使用模块 A 中的 SomeClass)。现在,我执行以下 python 脚本:

import A
import B
obj1 = A.SomeClass()
obj2 = B.AnotherClass()
obj2.func(obj1)

我收到以下错误:

Traceback (most recent call last):
  File "C:\bladiebla\script.py", line 8, in <module>
    obj2.func(obj1)
ArgumentError: Python argument types in
AnotherClass.func(AnotherClass, SomeClass)
did not match C++ signature:
func(class AnotherClass {lvalue}, class SomeClass)

Python 似乎不会自动在模块之间转换类。有谁知道如何解决这个问题?

最佳答案

我最近才开始摆弄 Boost.Python 并遇到了同样的问题。

查看以下文档的第 6 部分:

http://www.boost.org/doc/libs/1_47_0/libs/python/doc/building.html

6.1 - 动态二进制

该库包含一个类型转换注册表。 因为一个注册表在所有扩展模块之间共享,所以在一个动态加载的扩展模块中暴露给 Python 的类的实例可以传递给在另一个这样的模块中暴露的函数

我在使用静态二进制文件时遇到了与您遇到的相同类型的错误。一旦我更改为动态二进制文件,它就会编译并运行良好。

关于c++ - Boost Python 中的跨模块依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4439361/

相关文章:

python - Python 中的 "thread local storage"是什么,我为什么需要它?

python - 如何将 .pyc 文件转换为 .exe 文件

C++ 是否有任何线程安全的组件可以写入(比没有锁的线程安全类似物更快)?

c++ - 使用外部可执行文件作为管道的 Qt 'way' 是什么?

python - OpenCV:反转蒙版?

c++ - 如何使用 boost 二分法?

C++ - 为什么 boost::hash_combine 是组合散列值的最佳方式?

c++ - boost memory_order_consume 示例

c++ - 指向成员模板类的指针

c++ - 在线程之间共享变量的方法