亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何編譯多個 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 關注
  • 53 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號