为了账号安全,请及时绑定邮箱和手机立即绑定

如何编译多个 C++ 文件以将它们与 Python ctypes 一起使用?

如何编译多个 C++ 文件以将它们与 Python ctypes 一起使用?

慕田峪7331174 2022-07-26 09:31:03
我在 Windows 上编译多个 C++ 有一点问题。我在 C++ 中实现了四个类,用于使用 gmp 进行密码学。我想用 ctypes 从 Python 调用它们。extern我用关键字写了一个cpp文件:#include "integer.h"#include "modular_number.h"#include "padic_number.h"#include "rational_number.h"extern "C" {    __declspec(dllexport) ModNum* newModNum(const char * n, const char * p) { return new ModNum(Integer(n), Integer(p)); }    __declspec(dllexport) const char* getModValue(const ModNum& mod){ return mod.getValue().getValue(); }    __declspec(dllexport) RationalNum* newRationalNum(const char* mpq) { return new RationalNum(mpq); }    __declspec(dllexport) const char* getRationalValue(const RationalNum& rat){ return rat.getValue(); }    __declspec(dllexport) PadicNum* newPadicNum(const char* n, const char* base) { return new PadicNum(Integer(n), Integer(base)); }    __declspec(dllexport) const char* getPadicValue(const PadicNum& padic){ return padic.getValue().getValue(); }}我编译了我的文件:mingw32-g++ -fexceptions -g -fexpensive-optimizations -flto -O3 -Weffc++ -Wextra -Wall -std=c++14 -fPIC -Og -IC:\MinGW\include -flto -s -lgmp -lmpfr -lpthread -c -fPIC *.cpp -I"C:\Program Files\Python38-32\include" -I"C:\Program Files\Python38-32\libs"mingw32-g++.exe -shared -Wl,-dll -o numeric.dll *.o -lgmp -lmpfr -lgmpxx -static但是当我在 Python 中使用这些命令时:import ctypes;x = ctypes.DLL("./numeric.dll");该变量x不具有以下功能:newModNum,getModValue等...谁能告诉我我做错了什么?我没有错误,我不明白。我的其他文件是带有头文件和实现的常见 C++ 文件。提前致谢,祝您有美好的一天!
查看完整描述

1 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

ctypes函数在首次使用时导入。使用libc为例:


>>> import ctypes

>>> libc = ctypes.CDLL("libc.so.06")

>>> "printf" in dir(libc)

False

>>> libc.printf

<_FuncPtr object at 0x7f6512c23430>

>>> "printf" in dir(libc)

True

ctypes假设所有参数和返回值都是int. 您应该提供类型提示,这些提示也可以方便地导入函数。


import ctypes

x = ctypes.DLL("./numeric.dll")

x.newModNum.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # <-- also imports

x.newModNum.rettype = ctypes.c_void_p

并从行尾删除分号。它会导致 Python 程序员出现危险的血压峰值。


查看完整回答
反对 回复 2022-07-26
  • 1 回答
  • 0 关注
  • 54 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号