【问题标题】:c pointers and ctypesc 指针和 ctypes
【发布时间】:2016-07-19 11:20:54
【问题描述】:

所以,我有 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) 的结果总是一些负整数。 指针有问题,但我不知道是什么问题。 有没有人有任何想法?

【问题讨论】:

  • 向我们展示您的完整 C 和 C++ 代码。
  • 我编辑了问题,现在有完整的C和C++代码

标签: python c++ c ctypes


【解决方案1】:

因为AddC 是一个静态函数,所以指针不是你的问题。

您需要将double 值传递给AddC,并返回一个double 类型:

t.AddC.restype = c_double
t.AddC(a, c_double(2), c_double(3))

documentation for ctype 解释了这一切。

【讨论】:

    【解决方案2】:

    As stated in the documentation

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

    所以添加

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

    你会得到5.0

    【讨论】:

    • 2 和 3 可能作为整数传递,因此结果可能不是 5.0。
    • 哦,对,没错。谢谢。也许也应该设置argtypes
    • 其实你也得这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 2010-11-24
    • 2014-01-23
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多