c++ Python类型:错误:异常:存取违规写入

siv3szwd  于 2023-02-26  发布在  Python
关注(0)|答案(1)|浏览(136)

日安!
我正在尝试使用ctypes使我的小测试dll在python代码中工作。
下面是我的cppmul. cpp:

#include <iostream>

using namespace std;

extern "C" __declspec(dllexport) float cmul(int int_param, float float_param) {
    float return_value = int_param * float_param;
    std::cout << "In cmult: int: " << int_param << ", float: " << float_param << ", returning: " << return_value << std::endl;
    return return_value;
}

extern "C" __declspec(dllexport) void hello() {
    std::cout << "wheee" << std::endl;
    return;
}

我用下面的脚本构建它:

g++ -c cppmul.cpp
g++ -shared -o libcppmul.dll -Wl,-out-implib,libcppmul.a -Wl,--export-all-symbols -Wl,--enable-auto-image-base cppmul.o

然后在python脚本中,我只是加载dll并尝试调用函数:

# loads great
lib = ctypes.WinDLL(libname, winmode=1)
lib.hello.restype = None
# exception here
lib.hello()

并获得:OSError:异常:写入0x000000000009658时发生访问冲突
操作系统 windows 10 x64,Python 3.9 x64.
有什么建议吗?
我想问题可能是某种类型不匹配??但是hello()函数中没有类型,只有一个void作为返回和一个空参数列表。

cgfeq70w

cgfeq70w1#

我用winmode=1和MSVC编译器再现了崩溃。删除winmode=1并使用相对路径('./cppmul')工作正常。
请注意,CDLL是与默认__cdecl调用约定一起使用的正确函数。WinDLL用于__stdcall调用约定,但两者都适用于64位版本。这只对32位兼容性有影响。
下面是调用这两个函数的完整示例:

import ctypes as ct

lib = ct.CDLL('./cppmul')
lib.hello.argtypes = ()
lib.hello.restype = None
lib.cmul.argtypes = ct.c_int, ct.c_float
lib.cmul.restype = ct.c_float
lib.hello()
print(lib.cmul(2, 3.4))

输出:

wheee
In cmult: int: 2, float: 3.4, returning: 6.8
6.800000190734863

相关问题