我正在编写一个带有多个库的 Rust 项目。工作区中的其他库使用的一些库导出类型。除了 Rust crate,我还想将一些库暴露给 Python,使用pyo3crate生成 Python 绑定,这就是我遇到麻烦的地方。
问题如下。
假设我们有两个 Rust 库包producer, 和consumer。在 中producer,我们有一个简单的类型,MyClass它是公开可用的,并且是 Python 模块的一部分。在consumercrate 中,我有一些函数接受类型为 的对象MyClass,并对它们执行一些操作。这些函数在 Rust 中可用,并且还绑定到第二个 Python 模块中。
我可以MyClass在 Python 和 Rust 中创建对象。我可以正确调用 Rust 代码(例如,从另一个应用程序)中接受MyClass. 但是我不能从 Python调用consumer模块中接受类型对象的函数。换句话说,虽然我可以在 Rust 或 Python 中创建类型的对象并在 Rust crate 中使用它们,但我无法将对象从Python 模块传递到Python 模块。这样做会生成 a ,尽管对象将自己宣传为具有 type 。为什么?MyClassMyClassconsumerproducerconsumerTypeErrorMyClass
编辑:请参阅问题的底部以进行进一步调查。 …
考虑以下代码片段。
#include <stdio.h>
typedef struct s {
int _;
char str[];
} s;
s first = { 0, "abcd" };
int main(int argc, const char **argv) {
s second = first;
printf("%s\n%s\n", first.str, second.str);
}
Run Code Online (Sandbox Code Playgroud)
当我用GCC 7.2编译时,我得到:
$ gcc-7 -o tmp tmp.c && ./tmp
abcd
abcd
Run Code Online (Sandbox Code Playgroud)
但是,当我使用Clang(Apple LLVM版本8.0.0(clang-800.0.42.1))进行编译时,得到以下信息:
$ clang -o tmp tmp.c && ./tmp
abcd
# Nothing here
Run Code Online (Sandbox Code Playgroud)
为什么编译器之间的输出不同?我希望该字符串不会被复制,因为它是一个灵活的数组成员(类似于此问题)。为什么GCC实际上会复制它?
编辑
一些评论和答案表明这可能是由于优化。GCC可能second是的别名first,因此更新second应禁止GCC进行优化。我添加了一行:
second._ = 1;
Run Code Online (Sandbox Code Playgroud)
但这不会改变输出。