python - 当使用 -O 优化时,ctypes 返回错误值

标签 python c++ ctypes

具有函数 foo() 的 C++ 代码具有外部名称 dll_foo(),调用时返回值 10。

#include <iostream>

using namespace std;

int foo();

int main() {  
    cout << "Start" << endl;  
    return 0;
}

int foo() {
    return 10;
}

extern "C" {
    int dll_foo() {foo();}
}

这被编译成一个 .dll 以这种方式与 ctypes 一起使用(C++11 出于不相关的原因):

g++ -std=c++11 -O2 -static -shared main.cpp -o main.dll

然后使用 LoadLibrary 在 python 中调用,我也尝试设置 restype 但没有效果:

from ctypes import cdll, c_uint

lib = cdll.LoadLibrary("main.dll")
# lib.dll_foo.restype = c_uint
print(lib.dll_foo())

它每次打印一个看似随机的数字(16710260、6224116,...)。如果不使用优化,代码会返回正确的值。

最佳答案

我想你的意思是 int dll_foo() {return foo();}。没有它,结果确实是不确定的。

关于python - 当使用 -O 优化时,ctypes 返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230424/

相关文章:

python ctypes将指向结构的指针作为参数发送给 native 库

python - 如何使用 yum python API 列出、添加和删除存储库?

python - 什么是 Ruby 类方法的 Python 等价物?

python - 类型是否在 python 中创建类 'Object'

C++ vector 内存使用 - 它曾经被释放过吗?

python - 如何获取 ctypes.c_char_p 实例的指针地址

python - 如何使用 BeautilSoup 提取表信息?

c++ - 如何将 boost::numeric::ublas::vector 复制到矩阵?

c++ - 我怎样才能将一个类的填充字节归零?

python - 如何将 malloc 和 free 与 python ctypes 一起使用?