kjrkvc kjrkvc - 4 months ago 27
Python Question

c pointers and ctypes

So, I have C++ class that I wrap in C so I can use it in Python using ctypes.
Declaration of C++ class:

// 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 wrap:

// 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 script:

import ctypes
t = ctypes.cdll('../Debug/cdll.dll')
a = t.newTest()
t.AddC(a, 2, 3)


Result of t.AddC(a, 2, 3) is always some negative integer.
There is a problem with a pointer, but I do not know what is a problem.
Does anyone have any ideas?

ams ams
Answer

As AddC is a static function the pointer is not your problem.

You need to pass double values to AddC, and get a double type back:

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

The documentation for ctype explains all this.

Comments