I want to run a C++ function from python that returns an int* array by reference and converts it into a python list.
Here is the example C++ code:
#include "stdafx.h"
#include <iostream>
#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT int getResponse(int*& hash_list)
{
std::cout << hash_list << std::endl;
int* hashes = new int[3];
hashes[0] = 8;
hashes[1] = 9;
hashes[2] = 10;
hash_list = hashes;
std::cout << hash_list << std::endl;
std::cout << *hash_list << std::endl;
std::cout << *(hash_list + 1) << std::endl;
std::cout << *(hash_list + 2) << std::endl;
return 0;
}
DLLEXPORT void testDLL()
{
std::cout << "DLL can be read" << std::endl;
}
Here is my best attempt in python:
from ctypes import cdll, c_int, POINTER, ARRAY, byref
LIB = cdll.LoadLibrary("<path to DLL>")
LIB.testDLL()
func = LIB.getResponse
itype = c_int
func.argtypes = [POINTER(ARRAY(itype,3))]
func.restype = c_int
chashes = (itype * 3)(*[0,1,2])
print(chashes)
func(byref(chashes))
print(chashes)
print(list(chashes))
This is the output:
DLL can be read
<ctypes.c_long_Array_3 object at 0x000001B00FB7FEC8>
0000000100000000
000001B00DB0AC70
8
9
10
<ctypes.c_long_Array_3 object at 0x000001B00FB7FEC8>
[229682288, 432, 2]
This approach seems to have some success, however I think the initial array passed to the C++ function has invalid entries. And then the returned values are mangled anyway.
Is this possible with ctypes? Any suggestions would be appreciated.
I also tried using a c_void_p instead of the ARRAY. In that case it also seems to work, but I don't know how to turn the resulting pointer into a python list.