kjrkvc kjrkvc - 8 months ago 73
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
static double Add(double a, double b);

#include "stdafx.h"
#include "Test.h"

double Test::Add(double a, double b)
return a + b;

C wrap:

// cdll.h
#define WRAPDLL_API __declspec(dllexport)
#define WRAPDLL_API __declspec(dllimport)

#include "Test.h"
extern "C"
WRAPDLL_API struct TestC;

WRAPDLL_API TestC* newTest();
WRAPDLL_API double AddC(TestC* pc, double a, double b);

#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

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.