1

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?

asked Jul 19, 2016 at 11:20
2
  • Show us your complete C and C++ code. Commented Jul 19, 2016 at 11:23
  • 2
    I edited the question, now there is complete C and C++ code Commented Jul 19, 2016 at 11:30

2 Answers 2

2

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.

answered Jul 19, 2016 at 11:43
Sign up to request clarification or add additional context in comments.

Comments

1

As stated in the documentation

By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object.

So just add

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

and you'll get 5.0 instead.

answered Jul 19, 2016 at 11:43

3 Comments

2 and 3 are probably passed as integers, so the result might not be 5.0.
Oh right, that's true. Thanks. Maybe one should set argtypes as well.
Actually you have to do it like this

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.