As a complete novice with C++ I just created my first Dynamic Link Library following the MS tutorial found here
The header file reads as follows:
// 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);
};
}
Now, I want to read this file into Python ctypes. I do this using:
import ctypes as ctypes
MyDll = 'MathFuncsDll.dll'
MyFuncs = ctypes.cdll.LoadLibrary(MyDll)
Now, I'm struggling to actually access the functions. My intuition leads me to try
a = ctypes.c_double(54)
b = ctypes.c_double(12)
summation = MyFuncs.Add(a,b)
which returns the error
AttributeError: function 'Add' not found
Is my problem that the function is nested within the class MyMathFuncs
which is also within namespace MathFuncs
? How do I gain access to these functions?
For reference, below is the contents of the .cpp
file used to generate the dll
// 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;
}
}
You cannot access C++ classes and namespaces using the ctypes
. There is no standard binary interface for C++, as there is for C. Every compiler outputs it's own (different) binaries for the same C++ dynamic libraries. You can read more about it here .
The thing you can do (if you have to do it in C++) is do all your work in C++ and then write a tiny layer of C that wraps it and exposes it. Then you'll be able to access it using ctypes
. Again, you can read about it here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.