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

问题描述 投票:1回答:1

我在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不具有以下功能:newModNumgetModValue等...谁能告诉我我在做什么错?我没有错误,我也不明白。我的其他文件是带有标头和实现的常见C ++文件。

感谢您,祝您愉快!

python c++ ctypes gmp
1个回答
0
投票

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程序员中导致危险的血压峰值。

© www.soinside.com 2019 - 2024. All rights reserved.