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?
-
Show us your complete C and C++ code.user4759923– user47599232016年07月19日 11:23:04 +00:00Commented Jul 19, 2016 at 11:23
-
2I edited the question, now there is complete C and C++ codekjrkvc– kjrkvc2016年07月19日 11:30:25 +00:00Commented Jul 19, 2016 at 11:30
2 Answers 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.
Comments
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
restypeattribute 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.
3 Comments
argtypes as well.