Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用-O优化时,ctypes返回错误的值_Python_C++_Ctypes - Fatal编程技术网

Python 使用-O优化时,ctypes返回错误的值

Python 使用-O优化时,ctypes返回错误的值,python,c++,ctypes,Python,C++,Ctypes,具有函数foo()的C++代码,该函数具有外部名称dll\u 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();

具有函数
foo()
的C++代码,该函数具有外部名称
dll\u 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();}
}
然后使用LoadLibrary在python中调用,我也尝试过设置restype,但没有效果:

from ctypes import cdll, c_uint

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


它每次打印一个看似随机的数字(167102606224116,…)。如果没有使用优化,代码会返回正确的值。

我想你的意思是
int-dll_-foo(){return-foo();}
。没有它,结果实际上是未定义的。

我想你的意思是
intdll_foo(){returnfoo();}
。如果没有它,结果实际上是未定义的。

那么
dll\u foo()
return
语句在哪里?编译器不会打印关于在
dll\u foo
中不返回值的警告@eryksun Nope,它在未优化版本中工作有什么原因吗?使用
-Wall
编译,让g++通知您错误。@eryksun是的,我的错误,应该始终使用它作为开始,并且
dll_foo()的
return
语句在哪里
?编译器不会打印关于在
dll_foo
中不返回值的警告。@eryksun不,它在未优化版本中工作有什么原因吗?使用
-Wall
编译,让g++通知您错误。@eryksun是的,我的错误,应该总是用它开始工作,谢谢。知道它为什么在未优化的编译版本中工作吗?@Lobstw我想在未优化的版本中
foo()
返回标准寄存器
rax
中的值,而标准寄存器
dll\u foo
不会修改。@Lobstw:在优化关闭的情况下,编译器(可能)调用
foo
,它存放其返回值,然后
dll\u foo()
返回,并将该值放在返回值的正确位置。打开优化器后,编译器检测到您没有(直接)使用
foo()
返回的值,因此它完全消除了对
foo()
的调用。谢谢。知道它为什么在未优化的编译版本中工作吗?@Lobstw我想在未优化的版本中
foo()
返回标准寄存器
rax
中的值,而标准寄存器
dll\u foo
不会修改。@Lobstw:在优化关闭的情况下,编译器(可能)调用
foo
,它存放其返回值,然后
dll\u foo()
返回,并将该值放在返回值的正确位置。打开优化器后,编译器检测到您没有(直接)使用
foo()
返回的值,因此它完全消除了对
foo()
的调用。
from ctypes import cdll, c_uint

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