c指针和c类型 所以,我有C++类,我用C包,这样我就可以在python中使用cType。 C++类声明:< /P> // 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指针和c类型 所以,我有C++类,我用C包,这样我就可以在python中使用cType。 C++类声明:< /P> // 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; },python,c++,c,ctypes,Python,C++,C,Ctypes,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 do

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))
这本书解释了这一切。

默认情况下,假定函数返回C int类型。通过设置函数对象的
restype
属性,可以指定其他返回类型

所以只要加上

t.AddC.restype = c_double
t.AddC(a, 2.0, 3.0)

你会得到<代码> 5代码>代码。

展示你的完整的C和C++代码。我编辑了这个问题,现在有完整的C和C++代码2和3可能作为整数传递,所以结果可能不是5.0.OH,对,没错。谢谢也许你也应该设置
argtypes
。实际上你必须这样做