簡體   English   中英

構建DLL(MyMathFuncs)以在Python Ctypes中使用

[英]Build DLL (MyMathFuncs) for use in Python Ctypes

作為C ++的新手,我按照此處的MS教程創建了我的第一個動態鏈接庫。

頭文件的內容如下:

// 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 ++沒有C的標准二進制接口。每個編譯器針對相同的C ++動態庫輸出自己的(不同的)二進制文件。 您可以在此處了解更多信息。

可以做的事情(如果必須在C ++中完成)是在C ++中完成所有工作,然后編寫一個小的C層將其包裝並公開。 然后,您將可以使用ctypes訪問它。 同樣,您可以在這里閱讀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM