gpt4 book ai didi

python - 构建用于 Python Ctypes 的 DLL (MyMathFuncs)

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:34 25 4
gpt4 key购买 nike

作为 C++ 的完全新手,我刚刚按照找到的 MS 教程创建了我的第一个动态链接库 here

头文件内容如下:

// MathFuncsDll.h

namespace MathFuncs
{
class MyMathFuncs
{
public:
// Returns a + b
static __declspec(dllexport) double Add(double a, double b);

// Returns a - b
static __declspec(dllexport) double Subtract(double a, double b);

// Returns a * b
static __declspec(dllexport) double Multiply(double a, double b);

// Returns a / b
// Throws DivideByZeroException if b is 0
static __declspec(dllexport) double Divide(double a, double b);
};
}

现在,我想将这个文件读入 Python ctypes。我这样做使用:

import ctypes as ctypes

MyDll = 'MathFuncsDll.dll'
MyFuncs = ctypes.cdll.LoadLibrary(MyDll)

现在,我很难真正访问这些函数。我的直觉引导我去尝试

a = ctypes.c_double(54)
b = ctypes.c_double(12)

summation = MyFuncs.Add(a,b)

返回错误

AttributeError: function 'Add' not found

我的问题是该函数嵌套在 class MyMathFuncs 中,而它也在 namespace MathFuncs 中?我如何获得这些功能的访问权限?

作为引用,下面是用于生成dll的.cpp文件的内容

// MathFuncsDll.cpp
// compile with: /EHsc /LD

#include "MathFuncsDll.h"

#include <stdexcept>

using namespace std;

namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}

double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}

double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}

double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}

return a / b;
}
}

最佳答案

您不能使用 ctypes 访问 C++ 类和命名空间。 C++ 没有标准的二进制接口(interface),而 C 有。每个编译器都为相同的 C++ 动态库输出它自己的(不同的)二进制文件。您可以阅读更多相关信息 here .

可以做的事情(如果您必须在 C++ 中完成)是在 C++ 中完成所有工作,然后编写一个很小的 ​​C 层来包装它并公开它。然后您就可以使用 ctypes 访问它。同样,您可以阅读它 here

关于python - 构建用于 Python Ctypes 的 DLL (MyMathFuncs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18133257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com