因此,我将 C++ 类包装在 C 中,这样我就可以使用 ctypes 在 Python 中使用它。 C++类声明:
// Test.h
class Test
{
public:
static double Add(double a, double b);
};
//Test.cpp
#include "stdafx.h"
#include "Test.h"
double Test::Add(double a, double b)
{
return a + b;
}
C 换行:
// cdll.h
#ifndef WRAPDLL_EXPORTS
#define WRAPDLL_API __declspec(dllexport)
#else
#define WRAPDLL_API __declspec(dllimport)
#endif
#include "Test.h"
extern "C"
{
WRAPDLL_API struct TestC;
WRAPDLL_API TestC* newTest();
WRAPDLL_API double AddC(TestC* pc, double a, double b);
}
//cdll.cpp
#include "stdafx.h"
#include "cdll.h"
TestC* newTest()
{
return (TestC*) new Test;
}
double AddC(TestC* pc, double a, double b)
{
return ((Test*)pc)->Add(a, b);
}
Python 脚本:
import ctypes
t = ctypes.cdll('../Debug/cdll.dll')
a = t.newTest()
t.AddC(a, 2, 3)
t.AddC(a, 2, 3) 的结果总是一些负整数。 指针有问题,但我不知道是什么问题。 有人有什么想法吗?
最佳答案
因为 AddC
是一个静态函数,所以指针不是您的问题。
您需要将double
值传递给AddC
,并返回一个double 类型:
t.AddC.restype = c_double
t.AddC(a, c_double(2), c_double(3))
documentation for ctype解释了这一切。
关于python - c 指针和 ctypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38457079/