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

我在 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++ 文件。


提前致谢,祝您有美好的一天!


慕田峪7331174
浏览 55回答 1
1回答

幕布斯7119047

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)Truectypes假设所有参数和返回值都是int. 您应该提供类型提示,这些提示也可以方便地导入函数。import ctypesx = ctypes.DLL("./numeric.dll")x.newModNum.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # <-- also importsx.newModNum.rettype = ctypes.c_void_p并从行尾删除分号。它会导致 Python 程序员出现危险的血压峰值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python